Spring注記駆動第6節の@Profile環境注入Bean

20812 ワード

6.@Profile環境注入Bean@Profile注記、Springは現在の環境に基づいて、一連のコンポーネントを動的にアクティブ化し、切り替える機能を提供し、環境標識を付けたbeanは、この環境がアクティブ化されたときにのみコンテナに登録することができます.デフォルトはdefault環境で、構成クラスに書かれています.指定した環境の場合、構成クラス全体のすべての構成が有効になります.環境IDをマークしていないbeanは、どの環境でもロードされます.
プレゼンテーションシーン:
ログ管理インタフェースクラスを追加し、このインタフェースの下で異なる具体的なログ実装方式を実現し、異なる環境に応じて異なるログ実装クラスを注入する.例えば、現在、Slf4jBeanのインタフェースクラスがあり、Log4jBeanLogbackBeanの2つの実装があり、dev環境が使用される場合、Lo4jBeanを使用してログを管理し、prd環境が使用される場合、LogbackBeanを使用することを決定する.
  • 新規ログインタフェースクラスSlf4jBean.java
  • package com.ddf.spring.annotation.bean;
    
    /**
     * @author DDf on 2018/8/8
     *        profile           ,     ,        ,           
     */
    public interface Slf4jBean {
        void info(String str);
    }
  • 新規ログ実装クラスLog4jBean.java
  • package com.ddf.spring.annotation.bean;
    
    /**
     * @author DDf on 2018/8/8
     */
    public class Log4jBean implements Slf4jBean {
    
        @Override
        public void info(String str) {
            System.out.println(this.getClass().getName() + ": " + str);
        }
    }
  • 新しい別のログ実装クラスLogbackBean.java
  • package com.ddf.spring.annotation.bean;
    
    /**
     * @author DDf on 2018/8/8
     */
    public class LogbackBean implements Slf4jBean {
        @Override
        public void info(String str) {
            System.out.println(this.getClass().getName() + ": " + str);
        }
    }
  • は、ProfileConfiguration.javaの構成クラスを新設し、@Profileの注釈を使用して方法的に異なる環境に基づいて異なるクラスを注入する.実際には、これまで使用していた構成クラスAnnotationConfigurationを完全に使用することができるが、環境の切り替えには、IOCの容器の再起動が複数回行われているにすぎない.そのため、コンソールに大量の印刷があり、この構成クラスを引き続き使用すると、大量のログに現在のテストが表示され、非常に観察しにくいため、このブロックは単独で新しい構成クラス
  • を使用します.
    package com.ddf.spring.annotation.configuration;
    
    import com.ddf.spring.annotation.bean.Log4jBean;
    import com.ddf.spring.annotation.bean.LogbackBean;
    import com.ddf.spring.annotation.bean.Slf4jBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    
    /**
     * @author DDf on 2018/8/8
     *    2,               IOC  ,               ,     ,          ,
     *                ,                
     */
    @Configuration
    public class ProfileConfiguration {
    
        /**
         *                    
         *        dev,Log4jBean
         * @return
         */
        @Bean
        @Profile("dev")
        public Slf4jBean log4jBean() {
            return new Log4jBean();
        }
    
        /**
         *                    
         *        prd,   LogbackBean
         * @return
         */
        @Bean
        @Profile("prd")
        public Slf4jBean logbackBean() {
            return new LogbackBean();
        }
    }
  • 主起動クラスApplication.javaを修正し、テスト@profileの方法testProfile
  • を追加する.
    package com.ddf.spring.annotation;
    
    import com.ddf.spring.annotation.service.AutowiredService;
    import com.ddf.spring.annotation.service.LazyBeanService;
    import com.ddf.spring.annotation.service.PrototypeScopeService;
    import com.ddf.spring.annotation.service.UserService;
    import com.ddf.spring.annotation.bean.AutowiredBean;
    import com.ddf.spring.annotation.bean.FactoryPrototypeBean;
    import com.ddf.spring.annotation.bean.FactorySingletonBean;
    import com.ddf.spring.annotation.bean.Slf4jBean;
    import com.ddf.spring.annotation.configuration.AnnotationConfiguration;
    import com.ddf.spring.annotation.configuration.ProfileConfiguration;
    import com.ddf.spring.annotation.entity.User;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @author DDf on 2018/7/19
     */
    public class Application {
        public static void main(String[] args) {
            System.out.println("-----------------------IOC     -------------------------");
            //             IOC  ,                    ,             
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationConfiguration.class);
            System.out.println("-----------------------IOC       -------------------------
    "
    ); // IOC bean , bean printBeans(applicationContext); // @Scope bean testPrototypeScopeService(applicationContext); // bean @Lazy testLazyBeanService(applicationContext); // FactoryBean Prototype testFactoryBeanPrototypeBean(applicationContext); // @PropertySource @Value testPropertySourceValue(applicationContext); // @Autowired Bean testAutowired(applicationContext); // @Profile Bean testProfile(applicationContext); // applicationContext.close(); } /** * IOC Bean * @param applicationContext */ private static void printBeans(AnnotationConfigApplicationContext applicationContext) { String[] definitionNames = applicationContext.getBeanDefinitionNames(); // IOC bean bean for (String name : definitionNames) { // , , , getBean Object bean = applicationContext.getBean(name); System.out.println("bean name:" + name + ", type: " + bean.getClass()); } } /** * @Scope bean * * @param applicationContext */ public static void testPrototypeScopeService(ApplicationContext applicationContext) { System.out.println("
    ----------------------- @Scope -------------------------"
    ); UserService userService = (UserService) applicationContext.getBean("userService"); UserService userService1 = applicationContext.getBean(UserService.class); System.out.println(" bean UserService " + (userService == userService1)); PrototypeScopeService prototypeScopeService = applicationContext.getBean(PrototypeScopeService.class); PrototypeScopeService prototypeScopeService1 = applicationContext.getBean(PrototypeScopeService.class); System.out.println("PrototypeScopeService prototype scope : " + (prototypeScopeService == prototypeScopeService1)); System.out.println("----------------------- @Scope -------------------------
    "
    ); } /** * bean , 。 * IOC bean , bean , bean , 。 */ public static void testLazyBeanService(ApplicationContext applicationContext) { System.out.println("
    --------------- bean @Lazy ----------------------"
    ); LazyBeanService lazyBeanService = applicationContext.getBean(LazyBeanService.class); LazyBeanService lazyBeanService1 = applicationContext.getBean(LazyBeanService.class); System.out.println("lazyBeanService==lazyBeanService1?: " + (lazyBeanService == lazyBeanService1)); System.out.println("--------------- bean @Lazy ----------------------
    "
    ); } /** * FactoryBean Prototype , FactoryBean Bean * @param applicationContext */ public static void testFactoryBeanPrototypeBean(ApplicationContext applicationContext) { System.out.println("
    ---------- FactoryBean Prototype ----------"
    ); FactorySingletonBean factorySingletonBean = applicationContext.getBean(FactorySingletonBean.class); FactorySingletonBean factorySingletonBean1 = applicationContext.getBean(FactorySingletonBean.class); FactoryPrototypeBean factoryPrototypeBean = applicationContext.getBean(FactoryPrototypeBean.class); FactoryPrototypeBean factoryPrototypeBean1 = applicationContext.getBean(FactoryPrototypeBean.class); System.out.println(" factorySingletonBean==factorySingletonBean1?" + (factorySingletonBean==factorySingletonBean1)); System.out.println("Prototype factoryPrototypeBean==factoryPrototypeBean1?" + (factoryPrototypeBean==factoryPrototypeBean1)); System.out.println("---------- FactoryBean Prototype ----------
    "
    ); } /** * @PropertySource @Value * @param applicationContext */ public static void testPropertySourceValue(ApplicationContext applicationContext) { System.out.println("
    --------------- @PropertySource @Value ----------------"
    ); User user = applicationContext.getBean(User.class); System.out.println("user : " + user.toString()); System.out.println("--------------- @PropertySource @Value ----------------
    "
    ); } /** * IOC Bean, Bean * , @Autowired Bean * @Autowired Bean , Bean, Bean,Bean * @Autowired @Qualifier Bean, Bean @Primary, @Qualifier , * Bean {@link AutowiredService} * @param applicationContext */ public static void testAutowired(ApplicationContext applicationContext) { System.out.println("
    -------------- autowired -----------------"
    ); AutowiredBean autowiredBean = (AutowiredBean) applicationContext.getBean("autowiredBean"); AutowiredBean autowiredBean2 = (AutowiredBean) applicationContext.getBean("autowiredBean2"); System.out.println("autowiredBean: " + autowiredBean); System.out.println("autowiredBean2: " + autowiredBean2); System.out.println(autowiredBean == autowiredBean2); /** * , {@link com.ddf.spring.annotation.configuration.AnnotationConfiguration.autowiredBean2} */ AutowiredService autowiredService = applicationContext.getBean(AutowiredService.class); AutowiredBean autowiredServiceBean = autowiredService.getAutowiredBean(); System.out.println(" @Primay AutowiredService bean: " + autowiredServiceBean); AutowiredBean autowiredServiceBean2 = autowiredService.getQualifierAutowiredBean(); System.out.println(" @Qualifier Bean: " + autowiredServiceBean2); // @Resource AutowiredBean resourceAutowiredBean = autowiredService.getResourceAutowiredBean(); System.out.println(" @Resource autowiredBean: " + resourceAutowiredBean); AutowiredBean resourceAutowiredBean2 = autowiredService.getResourceAutowiredBean2(); System.out.println(" @Resource autowiredBean2: " + resourceAutowiredBean2); // @Inject UserService userService = autowiredService.getUserService(); System.out.println(" @Inject UserService: " + userService); System.out.println("-------------- autowired -----------------
    "
    ); } /** * Profile Bean * profile : * 1. java -Dspring.profiles.active=test * 2. , , ,spring-boot * @param applicationContext */ public static void testProfile(AnnotationConfigApplicationContext applicationContext) { System.out.println("------------------ @Profile-------------------------"); // IOC applicationContext = new AnnotationConfigApplicationContext(); // applicationContext.register(ProfileConfiguration.class); // profile applicationContext.getEnvironment().setActiveProfiles("dev"); // applicationContext.refresh(); // Bean Slf4jBean devLogBean = applicationContext.getBean(Slf4jBean.class); devLogBean.info(" "); applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(ProfileConfiguration.class); applicationContext.getEnvironment().setActiveProfiles("prd"); applicationContext.refresh(); Slf4jBean prdLogBean = applicationContext.getBean(Slf4jBean.class); prdLogBean.info(" "); System.out.println("------------------ @Profile-------------------------"); } }
  • の印刷ログは以下の通りである、まず使用されるdev環境を見ることができ、次にcom.ddf.spring.annotation.bean.Log4jBean: を印刷し、prd環境に切り替え、com.ddf.spring.annotation.bean.LogbackBean:
  • を印刷する.
    .......         ............
    ------------------  @Profile-------------------------
    PostConstructAndPreDestoryBean    ,  @PreDestroy           。。。。
    InitAndDisposableBean    ,  DisposableBean        ...........
    User         ....  @Bean destoryMethod      ......
    com.ddf.spring.annotation.bean.Log4jBean:     
    com.ddf.spring.annotation.bean.LogbackBean:     
    ------------------  @Profile-------------------------