Autowired Environment is null

后端 未结 4 1631
滥情空心
滥情空心 2020-11-28 08:42

I have an issue with connecting environment to my Spring project. In this class

@Configuration
@ComponentScan(basePackages = \"my.pack.offer.*\")
@PropertyS         


        
4条回答
  •  迷失自我
    2020-11-28 08:58

    Please put this code inside the class where you are trying to autowire the Environment

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    

    It solved my issue. Below I give you my class.

    @Configuration
    @EnableTransactionManagement
    public class DatabaseConfig {   
    /**
     * DataSource definition for database connection. Settings are read from the
     * application.properties file (using the env object).
     */
    @Bean
    public DataSource dataSource() {
    
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("db.driver"));
        dataSource.setUrl(env.getProperty("db.url"));
        dataSource.setUsername(env.getProperty("db.username"));
        dataSource.setPassword(env.getProperty("db.password"));
        return dataSource;
    }
    
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    
      @Autowired
      private Environment env;
    
    }
    

提交回复
热议问题