使用注解简化IoC的相关配置
使用注解来完成IoC,必须配置相关的解析器。
· 必须的配置
1、需要新增名字为context的命名空间,配置schema的位置。
2、配置解析器
配置<context:component-scan>中的base-package属性。
<context:component-scan>告诉Spring需要扫描使用注解管理的bean。
base-package属性告诉Spring去哪些包中扫描。(多个包之间用逗号隔开即可)
· 标注bean的注解
以下注解相当于<bean id="xxx" class="xxx.xxx">
@Controller:用于标注控制层组件(如Structs中的Action)
@Service:用于标注业务层组件。
@Repository:用于标注数据访问层组件,即DAO组件。
@Component:泛指组件,当组件不好归类时,可使用该注解进行标注。
这些注解都有value属性,相当于<bean>的id属性。
阅读源代码,可以发现@Controller、@Service、@Resository都打上了@Component注解。
实际上,在Spring看来,这些注解都是一样的。名称的不同只是为了便于程序员分类。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
*/
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
*/
String value() default "";
}
其余略。
使用@Component的限制:
1、不能运用到静态工厂方法和实例工厂方法,但是可以使用到FactoryBean。
2、对于没有源代码的类(框架内部的预定义类),只能用XML配置。
· 指定bean的作用域
@Scope
对其value值进行配置,相当于<bean>的scope属性。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
/**
* Specifies the scope to use for the annotated component/bean.
* @see ConfigurableBeanFactory#SCOPE_SINGLETON
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
*/
String value() default ConfigurableBeanFactory.SCOPE_SINGLETON;
// 其余略
}
· 初始化方法和销毁方法
@PostConstruct和@PreDestroy。分别标注在初始化方法和销毁方法上。
相当于<bean>的init-method和destory-method。但是这两个注解没有属性值(没必要有)。