Spring将所有的bean都纳入到IOC中创建、管理和维护,一个系统往往有成千上万的组件,如果需要手动将所有组件都放入spring容器中去管理,这样spring配置文件将变得非常冗余且庞大,管理也将十分不方便
在Spring2.5中引入了组件自动扫描机制,Spring 提供组件扫描(component scanning)功能。它能从classpath里自动扫描、侦测和实例化具有特定注解的组件。基本的注解是@Component,它标识一个受Spring管理的组件。其他特定的注解有@Repository、@Service和@Controller,它们分别标识了持久层、服务处和表现层的组件。
一、所需jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
二、spring的配置文件
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.springbean.*"/>
</beans>
激活组件扫描功能,自动扫描通过注解配置的组件
<context:component-scan base-package="com.springbean.*"/>
注:<context:component-scan>节点用于通知Spring容器扫描组件,base-package属性用于指定将要被扫描的组件所在的包名称。
三、注解类型
@Service 用于标注业务层组件;
@Repository 用于标注数据访问层组件;
@Controller 用于标注控制层组件(如:Struts中的action,springMVC的controller)
@Component 表示泛型组件,当组件不好归类的时候,我们可以使用这个组件进行注解。
1.biz类配置
@Service
@Component
public class UserBaseInfoBiz{
}
使用ApplicationContext对象的getBean()方法寻找组件。在之前的配置文件中会用<bean>标签的id属性去定义。通过注解Spring会将被标注注解的类名拿到,然后再将该类名的第一个字母变为小写,放到getBean()方法中。如:UserBaseInfoBiz类的组件Id就会是UserBaseInfoBiz获取时为context.getBean("userBaseInfoBiz");
也可以在注解之后添加自定义的类名
@Service("UserBaseInfoBiz")
@Component
public class UserBaseInfoBiz{
}
2.Dao类配置
@Repository
public class UserBaseInfoDao{
}
3.Controller类配置
@Controller
@RequestMapping("/user")
public class UserController {
}
设置组件的作用域范围,可以直接在为类添加注解的同时,运用另一个注解@Scope("prototype")来设置
@Service
@Scope("prototype")
public class UserBaseInfoBiz{
}
在使用注解时,为组件设置初始化和销毁方法
@Service
public class UserBaseInfoBiz{
@PostConstruct
public void addItem() {
System.out.println("初始化方法");
}
@PreDestroy
public void testItem() {
System.out.println("释放资源");
}
}
使用Spring自动扫描组件后进行依赖注入
运用注解@Resource和@Autowired,并为依赖对象设置名称,首先它会根据名称去找Spring自动扫描的并加入到Spring容器的组件(bean),如果有相同的名称,则进行依赖注入,如果没有相同的名称。则会根据类型区寻找组件。
参考文献:
http://blog.csdn.net/zhangzeyuaaa/article/details/22591991
http://blog.163.com/qqabc20082006@126/blog/static/2292852520091128103316534/