복붙노트

[SPRING] Spring 3.1 환경 설정 : 환경이 주입되지 않음

SPRING

Spring 3.1 환경 설정 : 환경이 주입되지 않음

봄 3.1 구성에 대해 다음을 사용하고 있습니다.

@Configuration
@EnableTransactionManagement
public class DataConfig {
    @Inject
    private Environment env;
    @Inject
    private DataSource dataSource;

    // @Bean
    public SpringLiquibase liquibase() {
        SpringLiquibase b = new SpringLiquibase();
        b.setDataSource(dataSource);
        b.setChangeLog("classpath:META-INF/db-changelog-master.xml");
        b.setContexts("test, production");
        return b;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean b = new LocalContainerEntityManagerFactoryBean();
        b.setDataSource(dataSource);
        HibernateJpaVendorAdapter h = new HibernateJpaVendorAdapter();
        h.setShowSql(env.getProperty("jpa.showSql", Boolean.class));
        h.setDatabasePlatform(env.getProperty("jpa.database"));

        b.setJpaVendorAdapter(h);
        return (EntityManagerFactory) b;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        PersistenceExceptionTranslationPostProcessor b = new PersistenceExceptionTranslationPostProcessor();
        // b.setRepositoryAnnotationType(Service.class);
        // do this to make the persistence bean post processor pick up our @Service class. Normally
        // it only picks up @Repository
        return b;

    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager b = new JpaTransactionManager();
        b.setEntityManagerFactory(entityManagerFactory());
        return b;
    }

    /**
     * Allows repositories to access RDBMS data using the JDBC API.
     */
    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource);
    }


    @Bean(destroyMethod = "close")
    public DataSource dataSource() {

        BasicDataSource db = new BasicDataSource();
        if (env != null) {
            db.setDriverClassName(env.getProperty("jdbc.driverClassName"));
            db.setUsername(env.getProperty("jdbc.username"));
            db.setPassword(env.getProperty("jdbc.password"));
        } else {
            throw new RuntimeException("environment not injected");
        }
        return db;
    }
}

문제는 변수 env가 주입되지 않고 항상 null이라는 것입니다.

환경 설정에 대해 아무 것도하지 않았기 때문에 필요한지 또는 방법을 모르겠습니다. 나는 온실 사례를 보았고 특별히 환경에 대한 것을 찾지 못했습니다. env가 주입되도록하려면 어떻게해야합니까?

관련 파일 :

// CoreConfig.java
@Configuration
public class CoreConfig {

    @Bean
    LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }

    /**
     * Properties to support the 'standard' mode of operation.
     */
    @Configuration
    @Profile("standard")
    @PropertySource("classpath:META-INF/runtime.properties")
    static class Standard {
    }

}


// the Webconfig.java
@Configuration
@EnableWebMvc
@EnableAsync
// @EnableScheduling
@EnableLoadTimeWeaving
@ComponentScan(basePackages = "com.jfd", excludeFilters = { @Filter(Configuration.class) })
@Import({ CoreConfig.class, DataConfig.class, SecurityConfig.class })
@ImportResource({ "/WEB-INF/spring/applicationContext.xml" })
public class WebConfig extends WebMvcConfigurerAdapter {


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(
                "/images/");
    }

    @Bean
    public BeanNameViewResolver beanNameViewResolver() {
        BeanNameViewResolver b = new BeanNameViewResolver();
        b.setOrder(1);
        return b;
    }

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver b = new InternalResourceViewResolver();
        b.setSuffix(".jsp");
        b.setPrefix("/WEB-INF/jsp/");
        b.setOrder(2);
        return b;
    }

    @Bean
    public CookieLocaleResolver localeResolver() {
        CookieLocaleResolver b = new CookieLocaleResolver();
        b.setCookieMaxAge(100000);
        b.setCookieName("cl");
        return b;
    }

    // for messages
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource b = new ResourceBundleMessageSource();
        b.setBasenames(new String[] { "com/jfd/core/CoreMessageResources",
                "com/jfd/common/CommonMessageResources",
                "com/jfd/app/AppMessageResources",
                "com/jfd/app/HelpMessageResources" });
        b.setUseCodeAsDefaultMessage(false);
        return b;
    }

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("org.springframework.web.servlet.PageNotFound", "p404");
        mappings.put("org.springframework.dao.DataAccessException",
                "dataAccessFailure");
        mappings.put("org.springframework.transaction.TransactionException",
                "dataAccessFailure");
        b.setExceptionMappings(mappings);
        return b;
    }

    /**
     * ViewResolver configuration required to work with Tiles2-based views.
     */
    @Bean
    public ViewResolver viewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
        viewResolver.setViewClass(TilesView.class);
        return viewResolver;
    }

    /**
     * Supports FileUploads.
     */
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(500000);
        return multipartResolver;
    }

    // for configuration
    @Bean
    public CompositeConfigurationFactoryBean myconfigurations()
            throws ConfigurationException {
        CompositeConfigurationFactoryBean b = new CompositeConfigurationFactoryBean();
        PropertiesConfiguration p = new PropertiesConfiguration(
                "classpath:META-INF/app-config.properties");
        p.setReloadingStrategy(new FileChangedReloadingStrategy());

        b.setConfigurations(new org.apache.commons.configuration.Configuration[] { p });
        b.setLocations(new ClassPathResource[] { new ClassPathResource(
                "META-INF/default-config.properties") });
        return b;
    }

    @Bean
    org.apache.commons.configuration.Configuration configuration()
            throws ConfigurationException {
        return myconfigurations().getConfiguration();
    }


// and the SecurityConfig.java
@Configuration
@ImportResource({ "/WEB-INF/spring/applicationContext-security.xml" })
public class SecurityConfig {

    @Bean
    public BouncyCastleProvider bcProvider() {
        return new BouncyCastleProvider();
    }

    @Bean
    public PasswordEncryptor jasyptPasswordEncryptor() {

        ConfigurablePasswordEncryptor b = new ConfigurablePasswordEncryptor();
        b.setAlgorithm("xxxxxx");
        return b;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder b = new org.jasypt.spring.security3.PasswordEncoder();
        b.setPasswordEncryptor(jasyptPasswordEncryptor());
        return b;
    }

}

applicationcontext.xml에서 config cache와 cassandra에 두 개의 XML 만 가져 왔으므로 중요하지 않을 수 있습니다.

해결법

  1. ==============================

    1.이유는 모르겠지만 @Resource 주석을 사용하면 효과가있었습니다. @Autowired는 항상 null을 반환했습니다.

    이유는 모르겠지만 @Resource 주석을 사용하면 효과가있었습니다. @Autowired는 항상 null을 반환했습니다.

  2. ==============================

    2.문제는 나를 기억하는 기능에 대한 봄 보안 때문입니다. 이 줄을 로 사용하면됩니다. 모든 것이 잘 작동합니다. 이 줄이 나타나면 다른 어떤 것보다 먼저 db를로드하려고 시도하고 env는 주입되지 않습니다.

    문제는 나를 기억하는 기능에 대한 봄 보안 때문입니다. 이 줄을 로 사용하면됩니다. 모든 것이 잘 작동합니다. 이 줄이 나타나면 다른 어떤 것보다 먼저 db를로드하려고 시도하고 env는 주입되지 않습니다.

  3. ==============================

    3.전체 Java EE 호환 서버를 사용하지 않는 경우 @Inject 지원을 추가하려면 프로젝트 클래스 경로에 javax.inject.jar를 포함시켜야합니다. 봄의 기본 @Autowired 주석을 사용해 볼 수도 있습니다.

    전체 Java EE 호환 서버를 사용하지 않는 경우 @Inject 지원을 추가하려면 프로젝트 클래스 경로에 javax.inject.jar를 포함시켜야합니다. 봄의 기본 @Autowired 주석을 사용해 볼 수도 있습니다.

  4. ==============================

    4.@jfd,

    @jfd,

    환경을 주입하지 못하게하는 구성에 문제가있는 것을 즉시 보지 않습니다.

    비어있는 @Configuration 클래스를 가지고 처음부터 시작한 다음 환경을 @Inject하면, 그것은 당신을 위해 작동합니까?

    그렇다면 어떤 시점에서 실패하기 시작합니까?

    가능한 한 가장 작은 구성으로 예제를 축소하여 복제 프로젝트로 제출 하시겠습니까? 지시 사항은 가능한 한 간단하게 만듭니다. https://github.com/SpringSource/spring-framework-issues#readme

    감사!

  5. ==============================

    5.여기에 언급 된 것과 마찬가지로 프로젝트에서 비슷한 오류가 발생했습니다. sessionFactory를 가져 오기 위해서는 afterproperties가 필요하다는 것도 알아 냈습니다. ... 그리고 예, 저는 스프링 보안도 사용하고 있습니다 (이것은 문제의 원인 일 수 있습니다).

    여기에 언급 된 것과 마찬가지로 프로젝트에서 비슷한 오류가 발생했습니다. sessionFactory를 가져 오기 위해서는 afterproperties가 필요하다는 것도 알아 냈습니다. ... 그리고 예, 저는 스프링 보안도 사용하고 있습니다 (이것은 문제의 원인 일 수 있습니다).

    내 @Configuration 주석 클래스는 Hibernate 기반 DAO를 포함하는 패키지의 경우 @ComponentScan을 사용하고 DAO가 사용하는 SessionFactory를 작성하는 경우 @Bean 주석이 적용된 메소드를 사용합니다. 런타임에 'sessionFactory'또는 'hibernateTemplate'을 찾을 수 없다는 예외가 발생합니다. SessionFactory가 생성되기 전에 DAO가 생성 된 것 같습니다. 한 가지 해결 방법은 구성 요소 검색 지시문을 XML 파일 ()에 넣고 @ComponentScan을 해당 파일의 @ImportResource로 바꾸는 것입니다.

    @Configuration
    //@ComponentScan(basePackages = "de.webapp.daocustomer", excludeFilters = {@ComponentScan.Filter(Configuration.class), @ComponentScan.Filter(Controller.class)})
    @ImportResource({"classpath*:componentScan.xml","classpath*:properties-config.xml","classpath*:security-context.xml"})
    public class AppConfig
    {
    ...
    @Bean
    public SessionFactory sessionFactory() throws Exception
    {
        AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
        bean.setDataSource(dataSource());
        bean.setPackagesToScan(new String[] {"de.webapp"});
        bean.setHibernateProperties(hibernateProps());
        bean.afterPropertiesSet();
        return bean.getObject();
    }
    

    또한 흥미로운 사실은 @ComponentScan이 포함되어 있으면 sessionFactory () 메서드에 설정된 중단 점에 도달하지 못했습니다!

  6. ==============================

    6.나는 또한 봄 - 사회 - 샘플 응용 프로그램과 비슷한 문제가 있었다.

    나는 또한 봄 - 사회 - 샘플 응용 프로그램과 비슷한 문제가 있었다.

    필드 레벨을 @Inject를 생성자 레벨로 변환 한 후 주입했다.

  7. from https://stackoverflow.com/questions/8070964/spring-3-1-configuration-environment-not-injected by cc-by-sa and MIT license