前面讲过我们可以通过spring配置文件中通过<bean/>节点来注入一个对象,但是一个大型的项目会有成千上万了类也有可能,如果我们一个个通过<bean/>节点来注入的或那么配置文件将非常庞大和臃肿。查找和维护起来也不方便。Spring从2.5版本引入了组件自动扫描机制他可以再类路径下寻找标注了@Component, @Service,@Controllor,@Repository注解的类,并把他们注入到spring容器中,要使用自动扫描机制我们需要打开配置信息
- <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="com.web.service.controllor"/>
- </beans>
我们约定@Service用于标注业务层组件,@Controllor用于标注控制层组件,@Repository用于标注数据层组件 。而@Component用于标注我们不好归类那些组件,比如一些工具类。当然我们只是约定这些注解的含义以便于区分不同的类的性质,其实他们起到的作用都是一样的,即使你用@Contollor来注解业务层类而用@service注解数据层类,spring也可以把他们成功的注入到容器中。
那我们知道我们知道注入spring容器中的对象都有一个name,然后我们可以通过 applicationContext.getBean(beanName)来从容器中取得bean对象,那么我们可能就有这样的疑问说通过组件扫描的方式注入的bean如何得到其对象呢。
通过组件扫描的方式注入的方式bean如果我们没有在加注解的时候没有指定bean名称,那么spring就默认以类的名称且首字母为小写作为bean name,当然我们也可以在注解上定义bean的name
@Service("userBiz") public class UserBizImpl implements UserBiz { …… }
我们也可以用注解@Scope来设置bean的作用域
@Service("userBiz") @Scope("prototype") public class UserBizImpl implements UserBiz { …… }
我们也可以用注解@PostConstructor来设置bean的init-method,用@PreDestory来设置destory 方法
@Service("userBiz") @Scope("prototype") public class UserBizImpl implements UserBiz { @PostContructor public void init() { System.out.println("init something"); } @PreDestory public void destory() { System.out.println("destory something"); } }