3

我想创建一个 DatabaseConfig 类来设置与数据库相关的东西(EntityManager、DataSource、TransactionManager)并获取我@Value("${property.name}")String字段上使用的属性

喜欢

@Configuration
public class DataBaseConfig {
    @Value("${hibernate.connection.username}")
    private String hibernateConnectionUsername;
    @Value("${hibernate.connection.password}")
    private String hibernateConnectionPassword;
    @Value("${hibernate.connection.driver_class}")
    private String hibernateConnectionDriverClass;
    @Value("${hibernate.connection.url}")
    private String hibernateConnectionUrl;
    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    @Value("${hibernate.showSql}")
    private String hibernateShowSql;
    @Value("${hibernate.generateDdl}")
    private String hibernateGenerateDdl;

// All my @Beans
}

问题是,所有这些字符串都是 NULL 而不是我的属性文件的值。

如果我将代码放入我的Application类(具有main和 中引用的类SpringApplication.run(Application.class, args);),则值注入有效

简而言之,@Value 适用于我的 Application 类,但不适用于我的自定义 @Configuration 类:(

有什么问题?还是需要更多信息?

更新:更多代码

方式 1,我的 Application.java 中的 DB Config 和 @Value 使用和不使用 PropertySourcesPlaceholderConfigurer

import java.beans.PropertyVetoException;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@ComponentScan
@EnableJpaRepositories
@EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class)
public class Application {
    public static void main(String[] args) throws Throwable {
        SpringApplication.run(Application.class, args);
    }

    // @Bean
    // public static PropertySourcesPlaceholderConfigurer properties() {
    // PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    // pspc.setLocations(new Resource[] { new ClassPathResource("application.properties") });
    // return pspc;
    // }

    /*****************************/
    @Value("${hibernate.connection.username}")
    private String hibernateConnectionUsername;

    @Value("${hibernate.connection.password}")
    private String hibernateConnectionPassword;

    @Value("${hibernate.connection.driver_class}")
    private String hibernateConnectionDriverClass;

    @Value("${hibernate.connection.url}")
    private String hibernateConnectionUrl;

    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    @Value("${hibernate.showSql}")
    private String hibernateShowSql;
    @Value("${hibernate.generateDdl}")
    private String hibernateGenerateDdl;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform(hibernateDialect);
        boolean generateDdl = Boolean.parseBoolean(hibernateGenerateDdl);
        boolean showSql = Boolean.parseBoolean(hibernateShowSql);
        vendorAdapter.setGenerateDdl(generateDdl);
        vendorAdapter.setShowSql(showSql);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setDataSource(dataSource());
        factory.setPackagesToScan("xxx");

        return factory;
    }

    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(hibernateConnectionUsername);
        dataSource.setPassword(hibernateConnectionPassword);
        try {
            dataSource.setDriverClass(hibernateConnectionDriverClass);
        } catch (PropertyVetoException e) {
            throw new IllegalArgumentException("Wrong driver class");
        }

        dataSource.setJdbcUrl(hibernateConnectionUrl);
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

方式2(我想要的),无论我在哪里拥有(应用程序或DatabaseConfig),它自己的文件(DatabaseConfing.java)中的DB Stuff都不起作用,PropertySourcesPlaceholderConfigurer因为它总是在DatabaseConfig中的@Beans之后被调用:(

import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import com.mchange.v2.c3p0.ComboPooledDataSource;


@Configuration
public class DatabaseConfig {
    @Value("${hibernate.connection.username}")
    private String hibernateConnectionUsername;
    @Value("${hibernate.connection.password}")
    private String hibernateConnectionPassword;
    @Value("${hibernate.connection.driver_class}")
    private String hibernateConnectionDriverClass;
    @Value("${hibernate.connection.url}")
    private String hibernateConnectionUrl;
    @Value("${hibernate.dialect")
    private String hibernateDialect;
    @Value("${hibernate.showSql}")
    private String hibernateShowSql;
    @Value("${hibernate.generateDdl}")
    private String hibernateGenerateDdl;

        // @Bean
        // public static PropertySourcesPlaceholderConfigurer properties() {
        // PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        // pspc.setLocations(new Resource[] { new ClassPathResource("application.properties") });
        // return pspc;
        // }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform(hibernateDialect);
        boolean generateDdl = Boolean.parseBoolean(hibernateGenerateDdl);
        boolean showSql = Boolean.parseBoolean(hibernateShowSql);
        vendorAdapter.setGenerateDdl(generateDdl);
        vendorAdapter.setShowSql(showSql);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setDataSource(dataSource());
        factory.setPackagesToScan("xxx");

        return factory;
    }

    @Bean
    public DataSource dataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(hibernateConnectionUsername);
        dataSource.setPassword(hibernateConnectionPassword);
        try {
            dataSource.setDriverClass(hibernateConnectionDriverClass);
        } catch (PropertyVetoException e) {
            throw new IllegalArgumentException("Wrong driver class");
        }
        System.err.println(hibernateConnectionUrl);
        dataSource.setJdbcUrl(hibernateConnectionUrl);
        return dataSource;
    }
}
4

2 回答 2

9

而不是您DatabaseConfig将以下内容添加application.propertiessrc/main/resources(从而删除您的DatabaseConfig课程)

#DataSource configuration
spring.datasource.driverClassName=<hibernateConnectionDriverClass>
spring.datasource.url=<hibernateConnectionUrl>
spring.datasource.username=<hibernateConnectionUsername>
spring.datasource.password=<hibernateConnectionPassword>

#JPA/HIbernate
spring.jpa.database-platform=<dialect-class>
spring.jpa.generate-ddl=<hibernateGenerateDdl>
spring.jpa.show-sql=<hibernateShowSql>

<placeholder>替换为实际值,spring-boot 会处理这个问题。

提示删除 C3P0 依赖项,因为 Spring 将为您(默认)提供 tomcat 连接池(它更新且更积极地维护,尽管名称在没有/外部的 Tomcat 的情况下完全可用)。

于 2013-11-18T10:33:44.490 回答
1
@Import({ CacheConfig.class, DatabaseConfig.class })
@ComponentScan(excludeFilters = @Filter(Configuration.class))

成功了。

于 2013-11-18T08:21:38.873 回答