1. 通过Setter注解绑定Bean的依赖
2. 通过属性注解绑定Bean的依赖
5. 通过注解设置Bean的自动绑定方式, 但注解无法设置默认自动绑定方式(类似XML下的default-autowire="byName"属性)
同一个Bean中的依赖关系,可以采用上述多种方式混合共存。这种情况出现在需要从已有的父类中扩展子类,而父类通常是class或者在jar包中的,此时你无法对父类使用注解,因为这需要在源代码中定义,所以你对父类的依赖项只能通过XML或者使用自动绑定机制,而对于扩展子类,你可以采用注解,XML设置或者某些依赖项则使用自动绑定的特性。
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>
<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设置或者某些依赖项则使用自动绑定的特性。