溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決

發(fā)布時(shí)間:2023-04-03 10:22:07 來(lái)源:億速云 閱讀:117 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

    Spring里的占位符

    spring里的占位符通常表現(xiàn)的形式是:

    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="url" value="${jdbc.url}"/>
    </bean>

    或者

    @Configuration
    @ImportResource("classpath:/com/acme/properties-config.xml")
    public class AppConfig {
        @Value("${jdbc.url}")
        private String url;
    }

    Spring應(yīng)用在有時(shí)會(huì)出現(xiàn)占位符配置沒(méi)有注入,原因可能是多樣的。

    本文介紹兩種比較復(fù)雜的情況。

    占位符是在Spring生命周期的什么時(shí)候處理的

    Spirng在生命周期里關(guān)于Bean的處理大概可以分為下面幾步:

    • 加載Bean定義(從xml或者從@Import等)

    • 處理BeanFactoryPostProcessor

    • 實(shí)例化Bean

    • 處理Bean的property注入

    • 處理BeanPostProcessor

    SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決

    當(dāng)然這只是比較理想的狀態(tài),實(shí)際上因?yàn)镾pring Context在構(gòu)造時(shí),也需要?jiǎng)?chuàng)建很多內(nèi)部的Bean,應(yīng)用在接口實(shí)現(xiàn)里也會(huì)做自己的各種邏輯,整個(gè)流程會(huì)非常復(fù)雜。

    那么占位符(${}表達(dá)式)是在什么時(shí)候被處理的?

    • 實(shí)際上是在org.springframework.context.support.PropertySourcesPlaceholderConfigurer里處理的,它會(huì)訪問(wèn)了每一個(gè)bean的BeanDefinition,然后做占位符的處理

    • PropertySourcesPlaceholderConfigurer實(shí)現(xiàn)了BeanFactoryPostProcessor接口

    • PropertySourcesPlaceholderConfigurer的 order是Ordered.LOWEST_PRECEDENCE,也就是最低優(yōu)先級(jí)的

    結(jié)合上面的Spring的生命周期,如果Bean的創(chuàng)建和使用在PropertySourcesPlaceholderConfigurer之前,那么就有可能出現(xiàn)占位符沒(méi)有被處理的情況。

    例子1

    Mybatis 的 MapperScannerConfigurer引起的占位符沒(méi)有處理

    首先應(yīng)用自己在代碼里創(chuàng)建了一個(gè)DataSource,其中${db.user}是希望從application.properties里注入的。

    代碼在運(yùn)行時(shí)會(huì)打印出user的實(shí)際值。

    @Configuration
    public class MyDataSourceConfig {
        @Bean(name = "dataSource1")
        public DataSource dataSource1(@Value("${db.user}") String user) {
            System.err.println("user: " + user);
            JdbcDataSource ds = new JdbcDataSource();
            ds.setURL("jdbc:h3:?/test");
            ds.setUser(user);
            return ds;
        }
    }

    然后應(yīng)用用代碼的方式來(lái)初始化mybatis相關(guān)的配置,依賴上面創(chuàng)建的DataSource對(duì)象

    @Configuration
    public class MybatisConfig1 {
    
        @Bean(name = "sqlSessionFactory1")
        public SqlSessionFactory sqlSessionFactory1(DataSource dataSource1) throws Exception {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            org.apache.ibatis.session.Configuration ibatisConfiguration = new org.apache.ibatis.session.Configuration();
            sqlSessionFactoryBean.setConfiguration(ibatisConfiguration);
    
            sqlSessionFactoryBean.setDataSource(dataSource1);
            sqlSessionFactoryBean.setTypeAliasesPackage("sample.mybatis.domain");
            return sqlSessionFactoryBean.getObject();
        }
    
        @Bean
        MapperScannerConfigurer mapperScannerConfigurer(SqlSessionFactory sqlSessionFactory1) {
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
            mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory1");
            mapperScannerConfigurer.setBasePackage("sample.mybatis.mapper");
            return mapperScannerConfigurer;
        }
    }

    當(dāng)代碼運(yùn)行時(shí),輸出結(jié)果是:

    user: ${db.user}

    為什么會(huì)user這個(gè)變量沒(méi)有被注入?

    分析下Bean定義,可以發(fā)現(xiàn)MapperScannerConfigurer它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor

    這個(gè)接口在是Spring掃描Bean定義時(shí)會(huì)回調(diào)的,遠(yuǎn)早于BeanFactoryPostProcessor。

    所以原因是:

    • MapperScannerConfigurer它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor,所以它會(huì)Spring的早期會(huì)被創(chuàng)建

    • 從bean的依賴關(guān)系來(lái)看,mapperScannerConfigurer依賴了sqlSessionFactory1,sqlSessionFactory1

    • 依賴了dataSource1MyDataSourceConfig里的dataSource1被提前初始化,沒(méi)有經(jīng)過(guò)PropertySourcesPlaceholderConfigurer的處理,所以@Value("${db.user}") String user 里的占位符沒(méi)有被處理

    要解決這個(gè)問(wèn)題,可以在代碼里,顯式來(lái)處理占位符:

    environment.resolvePlaceholders("${db.user}")

    例子2

    Spring boot自身實(shí)現(xiàn)問(wèn)題,導(dǎo)致Bean被提前初始化

    Spring Boot里提供了@ConditionalOnBean,這個(gè)方便用戶在不同條件下來(lái)創(chuàng)建bean。

    里面提供了判斷是否存在bean上有某個(gè)注解的功能。

    @Target({ ElementType.TYPE, ElementType.METHOD })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Conditional(OnBeanCondition.class)
    public @interface ConditionalOnBean {
        /**
         * The annotation type decorating a bean that should be checked. The condition matches
         * when any of the annotations specified is defined on a bean in the
         * {@link ApplicationContext}.
         * @return the class-level annotation types to check
         */
        Class<? extends Annotation>[] annotation() default {};

    比如用戶自己定義了一個(gè)Annotation:

    @Target({ ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation {
    }

    然后用下面的寫(xiě)法來(lái)創(chuàng)建abc這個(gè)bean,意思是當(dāng)用戶顯式使用了@MyAnnotation(比如放在main class上),才會(huì)創(chuàng)建這個(gè)bean。

    @Configuration
    public class MyAutoConfiguration {
        @Bean
        // if comment this line, it will be fine.
        @ConditionalOnBean(annotation = { MyAnnotation.class })
        public String abc() {
            return "abc";
        }
    }

    這個(gè)功能很好,但是在spring boot 1.4.5 版本之前都有問(wèn)題,會(huì)導(dǎo)致FactoryBean提前初始化。

    在例子里,通過(guò)xml創(chuàng)建了javaVersion這個(gè)bean,想獲取到j(luò)ava的版本號(hào)。

    這里使用的是spring提供的一個(gè)調(diào)用static函數(shù)創(chuàng)建bean的技巧。

    <bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
      <property name="targetClass" value="java.lang.System" />
      <property name="targetMethod" value="getProperties" />
    </bean>
    
    <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
      <property name="targetObject" ref="sysProps" />
      <property name="targetMethod" value="getProperty" />
      <property name="arguments" value="${java.version.key}" />
    </bean>

    我們?cè)诖a里獲取到這個(gè)javaVersion,然后打印出來(lái):

    @SpringBootApplication
    @ImportResource("classpath:/demo.xml")
    public class DemoApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
            System.err.println(context.getBean("javaVersion"));
        }
    }

    在實(shí)際運(yùn)行時(shí),發(fā)現(xiàn)javaVersion的值是null。

    這個(gè)其實(shí)是spring boot的鍋,要搞清楚這個(gè)問(wèn)題,先要看@ConditionalOnBean的實(shí)現(xiàn)。

    • @ConditionalOnBean實(shí)際上是在ConfigurationClassPostProcessor里被處理的,它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor

    • BeanDefinitionRegistryPostProcessor是在spring早期被處理的

    • @ConditionalOnBean的具體處理代碼在org.springframework.boot.autoconfigure.condition.OnBeanCondition

    • OnBeanCondition在獲取beanAnnotation時(shí),調(diào)用了beanFactory.getBeanNamesForAnnotation

    private String[] getBeanNamesForAnnotation(
        ConfigurableListableBeanFactory beanFactory, String type,
        ClassLoader classLoader, boolean considerHierarchy) throws LinkageError {
      String[] result = NO_BEANS;
      try {
        @SuppressWarnings("unchecked")
        Class<? extends Annotation> typeClass = (Class<? extends Annotation>) ClassUtils
            .forName(type, classLoader);
        result = beanFactory.getBeanNamesForAnnotation(typeClass);
    • beanFactory.getBeanNamesForAnnotation 會(huì)導(dǎo)致FactoryBean提前初始化,創(chuàng)建出javaVersion里,傳入的${java.version.key}沒(méi)有被處理,值為null。

    • spring boot 1.4.5 修復(fù)了這個(gè)問(wèn)題

    實(shí)現(xiàn)spring boot starter要注意不能導(dǎo)致bean提前初始化

    用戶在實(shí)現(xiàn)spring boot starter時(shí),通常會(huì)實(shí)現(xiàn)Spring的一些接口,比如BeanFactoryPostProcessor接口,在處理時(shí),要注意不能調(diào)用類似beanFactory.getBeansOfType,beanFactory.getBeanNamesForAnnotation 這些函數(shù),因?yàn)闀?huì)導(dǎo)致一些bean提前初始化。

    而上面有提到PropertySourcesPlaceholderConfigurer的order是最低優(yōu)先級(jí)的,所以用戶自己實(shí)現(xiàn)的BeanFactoryPostProcessor接口在被回調(diào)時(shí)很有可能占位符還沒(méi)有被處理。

    對(duì)于用戶自己定義的@ConfigurationProperties對(duì)象的注入,可以用類似下面的代碼:

    @ConfigurationProperties(prefix = "spring.my")
    public class MyProperties {
        String key;
    }
    public static MyProperties buildMyProperties(ConfigurableEnvironment environment) {
      MyProperties myProperties = new MyProperties();
    
      if (environment != null) {
        MutablePropertySources propertySources = environment.getPropertySources();
        new RelaxedDataBinder(myProperties, "spring.my").bind(new PropertySourcesPropertyValues(propertySources));
      }
    
      return myProperties;
    }

    讀到這里,這篇“SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI