Spring应用程序无法从属性源检索数据

时间:2016-12-22 00:23:04

标签: java spring spring-mvc

我尝试使用我的Spring应用程序中的Environment从application.properties文件中检索数据,但它无法正常工作。我无法通过Environment正确绑定数据。如果我使用如下所示的局部变量,我只能得到这个工作:

AppConfig.class吧!

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.victommasi.eshop.dao")
@PropertySource("classpath:application.properties")
public class AppConfig {

private static final String driverClass = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost/eshop";
private static final String username = "root";
private static final String password = "root";

private static final String dialect = "org.hibernate.dialect.MySQL5Dialect";
private static final String showSql = "true";
private static final String formatSql = "true";
private static final String hbm2dllAuto = "update";
private static final String packageToScan = "com.victommasi.eshop.model";


@Bean 
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);   
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", dialect);
    properties.put("hibernate.show_sql", showSql);
    properties.put("hibernate.format_sql", formatSql);
    properties.put("hibernate.hbm2ddl.auto", hbm2dllAuto);
    return properties;        
}


@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();     
    transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); 
    return transactionManager;

}

@Bean 
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
        entityManagerFactoryBean.setPackagesToScan(packageToScan);
        entityManagerFactoryBean.setJpaProperties(hibernateProperties());
        return entityManagerFactoryBean;
}

 }

我想要的AppConfig.class

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.victommasi.eshop.dao")
@PropertySource("classpath:application.properties")
public class AppConfig {

@Autowired
private Environment env;


@Bean 
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));   
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    return properties;        
}


@Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();     
    transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); 
    return transactionManager;

}

@Bean 
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
        entityManagerFactoryBean.setPackagesToScan(env.getProperty("packages.to.scan"));
        entityManagerFactoryBean.setJpaProperties(hibernateProperties());
        return entityManagerFactoryBean;
}

其他课程:

WebConfig.class

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.victommasi.eshop" })
public class WebConfig extends WebMvcConfigurerAdapter {

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

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setContentType("text/html;charset=UTF-8");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Bean(name = "filterMultipartResolver")
public CommonsMultipartResolver getMultipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(1048576);
    multipartResolver.setMaxInMemorySize(1048576);
    return multipartResolver;
}

 }

WebAppInitializer.class

public class WebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) throws ServletException {

    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(WebConfig.class, AppConfig.class, SecurityConfig.class);

    container.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
    dispatcherServlet.register(WebConfig.class);

    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

}

我知道这似乎很容易,我也跟着这个tutorial,但是不能完成这件事。

2 个答案:

答案 0 :(得分:1)

我没有经历过这一切,但似乎你错过了PropertySourcesPlaceholderConfigurer bean

  

自从Spring 3.1引入了新的@PropertySource注释以来,作为一个   向环境添加属性源的便利机制。   此注释将与基于Java一起使用   配置和@Configuration注释:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}

有了这个,您现在可以开始注入@Value注释的属性很简单:

@Value( "${jdbc.url}" )
private String jdbcUrl;

另一方面,考虑/查看spring-boot,您将获得以上所有内容(包括您共享的所有代码)以及免费更多内容,即零代码行

答案 1 :(得分:0)

阅读评论后,我查看了控制台,发现'application.properties'文件中的数据被带有空格的环境绑定到AppConfig.class。

堆栈跟踪:

Caused by: java.sql.SQLException: Access denied for user 'root      '@'localhost'

我认为这是绑定无效的原因。我的应用程序现在按我的意愿工作。感谢。