Подтвердить что ты не робот

Аутентифицированная среда равна нулю

У меня есть проблема с подключением к моему проекту Spring. В этом классе

@Configuration
@ComponentScan(basePackages = "my.pack.offer.*")
@PropertySource("classpath:OfferService.properties")
public class PropertiesUtil {
    @Autowired
    private Environment environment;



    @Bean
    public String load(String propertyName)
    {
        return environment.getRequiredProperty(propertyName);
    }
}
Окружение

всегда равно null.

4b9b3361

Ответ 1

Автосообщение происходит позже, чем load() вызывается (по какой-либо причине).

Обходной путь заключается в реализации EnvironmentAware и полагаться на Spring вызов метода setEnvironment():

@Configuration
@ComponentScan(basePackages = "my.pack.offer.*")
@PropertySource("classpath:OfferService.properties")
public class PropertiesUtil implements EnvironmentAware {
    private Environment environment;

    @Override
    public void setEnvironment(final Environment environment) {
        this.environment = environment;
    }

    @Bean
    public String load(String propertyName)
    {
        return environment.getRequiredProperty(propertyName);
    }
}

Ответ 2

Измените @Autowired на @Resource (из javax.annotation) и сделайте его public например:

@Configuration
@PropertySource("classpath:database.properties")
public class HibernateConfigurer {

    @Resource
    public Environment env;

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("database.driverClassName"));
        dataSource.setUrl(env.getProperty("database.url"));
        dataSource.setUsername(env.getProperty("database.username"));
        dataSource.setPassword(env.getProperty("database.password"));
        dataSource.setValidationQuery(env.getProperty("database.validationQuery"));

        return dataSource;
    }
}

И вы должны зарегистрировать свой класс конфигурации в WebApplicationInitializer таким образом

AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ApplicationConfigurer.class); //ApplicationConfigurer imports HibernateConfigurer

Это работает для меня! Вы можете проверить тестовый проект, который я сделал.

Ответ 3

Пожалуйста, поместите этот код внутри класса, где вы пытаетесь autwire Environment

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

Это решило мою проблему. Ниже я даю вам свой класс.

@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;

}