组件扫描:Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件。
特定的组件包括:
@Component:基本注解,标志了一个受Spring管理的组件
@Respository:标识持久层组件组件
@Service:标识服务(业务层)层组件
@Controller:标识表现层组件
组件类使用特定的注解后,还需要在Spring的配置文件中声明<context:component-scan>
代码:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="annotation"></context:component-scan>
</beans>
- base-package 属性指定一个需要扫描的基类包,Spring容器将会扫描这个基类包里及其子包中的所有类。
- 当需要扫描多个包时,可以使用逗号分隔
- 如果近希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类
例如:
<context:component-scan base-package="annotation" resource-pattern="repository/*.class"></context:component-scan>
到时候就只扫描repository包下面的类。
- <context:include-filter> 子节点表示要包含的目标类
- <context:exclude-filter>子节点表示要排除在外的目标类
- <context:component-scan> 下可以拥有若干个<context:include-filter>和<context:exclude-filter>子节点 。 <context:include-filter>这个要跟 use-default-filters="true" 这个配合使用。
--------------------------------------------------------------
组件的装配:<context:component-scan>元素还会注册AutowiredAnnotationBeanPostProcessor【bean后置处理器】实例,这个实例可以自动装配具有@Autowired和@Resource、@Inject注解的属性。
使用@Autowired自动装配Bean: @Autowired 注解自动装配具有兼容类型的单个Bean属性。
- 它可以放在 构造器,普通字段(即使是非public)和 一切具有参数的方法都可以
- 默认情况下,所有使用@Autowire注解的属性都需要被设置,当Spring找不到匹配的bean装配属性是,会抛异常。
如果某个属性可以不被设置,则可以设置@Autowire注解的required属性为false【@Autowire(required = false) 那么打印是null】
- 默认情况下当IOC容器里存在多个类型兼容的bean时,通过类型的自动装配将无法工作。此时可以在@Qualifiter注解里提供Bean的名称。Spring允许对方法的入参标注@Qualifilter 已指定注入bean的名称。
@Service public class UserService { @Autowired @Qualifier("userJDBCRepository") private UserRepository userRepository; public void add(){ System.out.println("UserService add..."); userRepository.save(); } }
入参标注:@Service public class UserService { // @Autowired // @Qualifier("userJDBCRepository") private UserRepository userRepository; @Autowired public void setUserRepository(@Qualifier("userJDBCRepository")UserRepository userRepository) { this.userRepository = userRepository; } public void add(){ System.out.println("UserService add..."); userRepository.save(); } }
- @Autowired注解可以应用在数组,集合,map上:
- 数组类型: 将会把所有匹配的bean进行自动装配
- 集合属性: 读取该集合的类型信息,然后自动装配与之兼容的bean
- Java.util.map:bean的名称作为键值(string),内容作为value