programing

자동 배선 환경이 null입니다.

codeshow 2023. 8. 30. 22:20
반응형

자동 배선 환경이 null입니다.

저는 제 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입니다.

자동 배선은 다음 시간 이후에 발생합니다.load()(어떤 이유로) 호출됩니다.

해결 방법은 다음과 같습니다.EnvironmentAware그리고 Spring calling에 의지합니다.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);
    }
}

바꾸다@Autowiredfor(javax.communication에서)를 생성합니다.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;
    }
}

그리고 WebApplication에 구성자 클래스를 등록해야 합니다.이 방법으로 초기화

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

나한테 효과가 있어요!당신은 제가 만든 테스트 프로젝트를 확인하는 것이 좋을 것입니다.

저는 컨스트럭터 주입과 같은 문제를 해결했습니다.

@Configuration
@PropertySource("classpath:my.properties")
public class MyConfig {
    private Environment environment;

    public MyConfig(Environment environment) {
        this.environment = environment
    }

    @Bean
    public MyBean myBean() {
        return new MyBean(environment.getRequiredProperty("srv.name"))
    }
}

나중에 (특성이 적절하게 주입되도록) 다음과 같이 단순화했습니다.

@Configuration
@PropertySource("classpath:my.properties")
public class MyConfig {
    private String serviceName;

    public MyConfig(Environment ignored) {
        /* No-op */
    }

    @Value("${srv.name}")
    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean(requireNonNull(serviceName)); // NPE without environment in constructor
    }
}

깔끔하고 간편한 기능:또한 호출할 수 있습니다.@PostConstruct방법:

@Autowired
private Environment env;

private String appPropertyValue;

@PostConstruct
private void postConstruct() {
    this.appPropertyValue = env.getProperty("myProperty");
}

이 코드를 환경 자동 배선을 시도하는 클래스 안에 넣으십시오.

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

}

언급URL : https://stackoverflow.com/questions/19421092/autowired-environment-is-null

반응형