我们自己的组件如何使用 Spring Ioc 底层组件

2021-04-02  本文已影响0人  尘埃里的玄

假如我们自己的组件需要使用 ApplicationContext 等,我们可以通过实现 XXXAware 接口来实现

@Component
public class TestCompent implements ApplicationContextAware, BeanNameAware {
    private ApplicationContext applicationContext;

    @Override
    public void setBeanName(String name) {
        System.out.println("current bean name is :【" + name + "】");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

扩展: @Profile 注解
通过@Profile 注解,根据环境来激活标识不同的 Bean

@Configuration
@PropertySource(value = {"classpath:ds.properties"})
public class MainConfig implements EmbeddedValueResolverAware {
    @Value("${ds.username}")
    private String userName;
    @Value("${ds.password}")
    private String password;
    private String jdbcUrl;
    private String classDriver;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.jdbcUrl = resolver.resolveStringValue("${ds.jdbcUrl}");
        this.classDriver = resolver.resolveStringValue("${ds.classDriver}");
    }//标识为测试环境才会被装配 @Bean @Profile(value = "test") public DataSource testDs() { return buliderDataSource(new DruidDataSource()); }//标识开发环境才会被激活 @Bean @Profile(value = "dev") public DataSource devDs() { return buliderDataSource(new DruidDataSource()); }//标识生产环境才会被激活 @Bean @Profile(value = "prod") 
        public DataSource prodDs() { return buliderDataSource(new DruidDataSource()); }
        private DataSource buliderDataSource(DruidDataSource dataSource) {
                  dataSource.setUsername(userName); 
                  dataSource.setPassword(password);
                  dataSource.setDriverClassName(classDriver); 
                  dataSource.setUrl(jdbcUrl);
                  return dataSource;
} }

激活切换环境的方法

上一篇 下一篇

猜你喜欢

热点阅读