Spring_11_使用注解简化IoC

使用注解简化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。但是这两个注解没有属性值(没必要有)。
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值