一.IOC容器:
BeanFactory提供了配置框架和基本的功能,ApplicationContext添加了更多的特别的功能
Bean的概念:
bean是一个被Spring IOC容器实例化,组装和管理的对象
配置Bean:xml配置,java注解,java code
传统的是用xml配置
可以使用的数据:类(POJOS)+配置文件=实例准备使用
1.基于注解的容器配置
注解注入是在xml配置之前执行的,后者将会覆盖前者的配置
@Required:
适用于bean属性的设置方法,受影响的bean属性必须在配置时被填充
@Autowire:
利用@Autowire注解进行构造
2.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
id作为bean的标识,class指向全局限定类名
3.java-based-configuration:
1.2.2 实例化容器
提供给ApplicationContext构造器的位置路径,允许容器从各种外部资源加载配置元数据
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
service的xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
dao层的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
</beans>
通常一个xml文件配置包含结构的一层
1.2.3使用容器:
ApplicationContext是一个高级工厂的接口,它能维护不同的bean,及其依赖项的注册表
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();