部分内容摘自:http://jinnianshilongnian.iteye.com/blog/1752171
Spring IoC容器目的就是管理Bean,这些Bean将根据配置文件中的Bean定义进行创建,<bean>标签主要用来进行Bean定义
Bean定义在容器内部由BeanDefinition对象表示.
Bean的命名
可以用id或name指定。
<bean
id=” bean”
class=” cn.javass.spring.chapter2.helloworld.HelloImpl”/>
<bean
name=” bean”
class=” cn.javass.spring.chapter2.helloworld.HelloImpl”/>
public void test3() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("chapter2/namingbean3.xml");
//根据name获取bean
HelloApi bean = beanFactory.getBean("bean", HelloApi.class);
bean.sayHello();
}
实例化Bean
使用构造器实例化Bean
<bean name="bean1" class="cn.javass.spring.chapter2.HelloImpl2"/>
<bean name="bean2" class="cn.javass.spring.chapter2.HelloImpl2">
<!-- 指定构造器参数 -->
<constructor-arg index="0" value="Hello Spring!"/>
</bean>
<bean id="messageProvider" class = "com.apress.prospring3.ch4.ConfigurableMessageProvider"
c:_0 = "This is c:message" />
使用静态工厂方式实例化Bean
<bean id="bean3" class="cn.javass.spring.chapter2.HelloApiStaticFactory"
factory-method="newInstance">
<constructor-arg index="0" value="Hello Spring!"/>
</bean>
使用实例工厂方法实例化Bean
<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->
</bean>
<!-- the bean to be created via the factory bean -->
<bean id="clientService"
factory-bean="serviceLocator"
factory-method="createClientServiceInstance"/>
public class DefaultServiceLocator {
private static ClientService clientService = new ClientServiceImpl();private DefaultServiceLocator() {}public ClientService createClientServiceInstance() {return clientService;}
}