在 spring 中的 java bean class 中设置数据库配置的方法是什么?

What is the way to setup Database configuration inside java bean class in spring?

我想在 java 配置 bean class 中设置我的数据库相关配置。有人可以帮助我提供带有相关注释的简单代码示例吗?

提问前请在网上搜索答案。

您可以使用以下示例代码。我想你可以得到更好的主意。

@Configuration
@ComponentScan(basePackages = {""})
@EnableTransactionManagement
@PropertySources(value = {@PropertySource(value = {"<propertyfile>"})})
public class ModulesConfig {

    private static final Logger log = LoggerFactory.getLogger(ModulesConfig.class);

    @Autowired
    private Environment environment;

    @Bean(destroyMethod = "close")
    public BoneCPDataSource getDataSource() {
        BoneCPDataSource dataSource = new BoneCPDataSource();
        dataSource.setDriverClass(environment.getProperty("database.driver"));
        dataSource.setJdbcUrl(environment.getProperty("database.url"));
        dataSource.setUsername(environment.getProperty("database.username"));
        dataSource.setPassword(environment.getProperty("database.password"));
        dataSource.setIdleConnectionTestPeriodInMinutes(30);
        dataSource.setMaxConnectionsPerPartition(5);
        dataSource.setMinConnectionsPerPartition(2);
        dataSource.setPartitionCount(3);
        dataSource.setAcquireIncrement(2);
        dataSource.setStatementsCacheSize(100);

        return dataSource;
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

        Properties jpaProperties = new Properties();
        jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        jpaProperties.setProperty("hibernate.showSql", "false");

        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(getDataSource());
        em.setPersistenceUnitName("entityManagerFactory");
        em.setPackagesToScan("<packages>");
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(jpaProperties);
        em.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);

        return em;
    }

}