使用Spring绑定的五种方式

1. 通过Setter注解绑定Bean的依赖
public class CustomAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {


    private AccountManager accountManager;


    @Autowired
    public void setAccountManager(AccountManager accountManager) {
		logger.info("setAccountManager in " + getClass().getName());
		this.accountManager = accountManager;
    }
}


2. 通过属性注解绑定Bean的依赖
public class CustomAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {


    @Autowired
    private AccountManager accountManager;


    public void setAccountManager(AccountManager accountManager) {
		logger.info("setAccountManager in " + getClass().getName());
		this.accountManager = accountManager;
    }
}

3. 通过XML配置绑定Bean的依赖

<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
	default-lazy-init="true">

<bean id="myAuthenticationFilter" 
	class="com.techpubs.techrevmanager.web.login.CustomAuthenticationProcessingFilter">
   	
	<property name="accountManager" ref="accountManager" />
</bean>

</beans>



4. 通过XML设置Bean自动绑定方式,此时无需通过前面3种设置也可设置依赖项。(如果byName,就是按照Bean的名称自动匹配)

<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
	default-lazy-init="true" default-autowire="byName">

<bean id="myAuthenticationFilter" autowire="byName"
	class="com.techpubs.techrevmanager.web.login.CustomAuthenticationProcessingFilter"/>

</bean>


5. 通过注解设置Bean的自动绑定方式, 但注解无法设置默认自动绑定方式(类似XML下的default-autowire="byName"属性)
@Configuration
// 注解Configuration的作用相当于一个applicationContext.xml
public class AppConfig {

    @Bean(autowire = Autowire.BY_NAME)
    // 如果不指定Bean注解的name属性,则默认与注解方法的名称一致
    public CustomAuthenticationProcessingFilter getCustomAuthenticationProcessingFilter() {
	return new CustomAuthenticationProcessingFilter();
    }

}

 

同一个Bean中的依赖关系,可以采用上述多种方式混合共存。这种情况出现在需要从已有的父类中扩展子类,而父类通常是class或者在jar包中的,此时你无法对父类使用注解,因为这需要在源代码中定义,所以你对父类的依赖项只能通过XML或者使用自动绑定机制,而对于扩展子类,你可以采用注解,XML设置或者某些依赖项则使用自动绑定的特性。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值