spring bean的获取方式

本文介绍了一个用于在Spring框架中方便获取ApplicationContext的工具类——SpringContextHolder。该工具类通过静态变量保存ApplicationContext,使得开发者可以在项目的任何位置轻松地获取到所需的Bean实例。

private static Demo demo = ((Demo)SpringContextHolder.getBean("demo"));


/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
 * 
 */
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        if (logger.isDebugEnabled()){
            logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
     */
    @Override
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }

    /**
     * 检查ApplicationContext不为空.
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    }
}
SpringBean 的注入方式主要分为基于注解和基于 XML 两种类型,以下为你详细介绍: ### 使用注解注入 Bean - **使用注解(@Component、@Service、@Repository、@Controller)和 @Autowired**:`@Component` 是一个通用的注解,用于将类标记为 Spring 管理的 Bean。`@Service`、`@Repository` 和 `@Controller` 是 `@Component` 的特定形式,分别用于服务层、数据访问层和表现层。`@Autowired` 用于自动装配 Bean。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service class MyService { private MyRepository myRepository; @Autowired public MyService(MyRepository myRepository) { this.myRepository = myRepository; } } ``` - **使用 @Configuration 和 @Bean**:`@Configuration` 用于标记一个类为配置类,`@Bean` 用于在配置类中定义 Bean。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration class AppConfig { @Bean public MyBean myBean() { return new MyBean(); } } ``` - **使用构造函数注入**:通过构造函数将依赖的 Bean 注入到目标 Bean 中。 ```java class MyBean { private AnotherBean anotherBean; public MyBean(AnotherBean anotherBean) { this.anotherBean = anotherBean; } } ``` - **使用 @Value 注入属性值**:`@Value` 用于注入属性值,可以从配置文件或环境变量中获取。 ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component class MyComponent { @Value("${my.property}") private String myProperty; } ``` - **使用 @Primary 标注优先注入的 Bean**:当有多个候选 Bean 时,使用 `@Primary` 标注的 Bean 将被优先注入。 ```java import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component @Primary class PrimaryBean implements MyInterface { // 实现接口方法 } ``` ### 基于 XML 注入 Bean - **构造器注入**:通过构造函数注入依赖的 Bean。 ```xml <bean id="myBean" class="com.example.MyBean"> <constructor-arg ref="anotherBean"/> </bean> ``` - **Setter 注入**:通过 setter 方法注入依赖的 Bean。 ```xml <bean id="myBean" class="com.example.MyBean"> <property name="anotherBean" ref="anotherBean"/> </bean> ``` - **接口注入(与 Spring 的 FactoryBean 结合使用)**:通过实现 `FactoryBean` 接口来创建 Bean。 ```java import org.springframework.beans.factory.FactoryBean; import org.springframework.stereotype.Component; @Component class MyFactoryBean implements FactoryBean<MyBean> { @Override public MyBean getObject() throws Exception { return new MyBean(); } @Override public Class<?> getObjectType() { return MyBean.class; } } ``` - **集合注入**:注入集合类型的依赖。 ```xml <bean id="myBean" class="com.example.MyBean"> <property name="myList"> <list> <ref bean="bean1"/> <ref bean="bean2"/> </list> </property> </bean> ``` - **自动装配(Autowiring)注入**:Spring 自动根据类型或名称进行 Bean 的装配。 ```xml <bean id="myBean" class="com.example.MyBean" autowire="byType"/> ``` - **引入(inner beans)**:在一个 Bean 定义中嵌套另一个 Bean 定义。 ```xml <bean id="myBean" class="com.example.MyBean"> <property name="innerBean"> <bean class="com.example.InnerBean"/> </property> </bean> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值