spring boot中db配置的区别是什么

问题描述 投票:1回答:1

1)这是类级配置(@configuration)。为什么我们需要这个样板代码

@Configuration
@EnableJpaRepositories(basePackages = {"xxx.xxx.xxx.core.dao"})
@EnableTransactionManagement
public class Repository {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/xxxx");
        dataSource.setUsername("xxxx");
        dataSource.setPassword("xxxx");

        return dataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("xx.xxxx.xxxx.xxxx.domain");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

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

2)此选项也正常工作.spring启动将占用其余代码,它将采用application.property文件进行配置

  @Configuration
@EnableJpaRepositories(basePackages = {"xxx.xxx.xxx.core.dao"})
@EnableTransactionManagement
@SpringBootApplication
@EnableCaching
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {

        ConfigurableApplicationContext app = SpringApplication.run(Application.class, args);

    } 

}

哪一个是好习惯,为什么我们需要为数据库配置创建一个类(选项1)以及spring将如何处理所有配置(选项2)

spring-boot spring-data spring-data-jpa
1个回答
0
投票

这是类级配置(@configuration)。为什么我们需要这个样板代码

这些样板代码不是强制性的。您只在特定情况下执行此操作。例如,如果您不希望spring-boot为您执行自动配置(使用application.properties中的默认值或值)。 另一个例子是当您在应用程序中有多个数据库连接时。在这种情况下,springboot的自动配置没有多大帮助,因此你会这样做。不是一次,而是与您拥有的数据库数量一样多。

哪一个是好习惯,为什么我们需要为数据库配置创建一个类(选项1)以及spring将如何处理所有配置(选项2)

正如您可能知道的那样,spring-boot主要是自以为是。这意味着,它会根据您在pom中添加的依赖项假设很多内容。即使您没有在属性文件中添加任何内容,它仍会尝试连接到本地主机上的数据库和一些预定义端口,只要它遇到您的pom中的数据库依赖项。

所以答案是“它取决于”。这取决于很多事情,无论你有一个还是多个数据源,还想要完全控制数据库配置的完成方式......等等

© www.soinside.com 2019 - 2024. All rights reserved.