你如何在 Spring-boot 中自动装配/注入你的数据源? [英] How do you autowire/inject your datasource in Spring-boot?
问题描述
我已经使用 Spring boot 一段时间了,在我看到的每个示例中,数据源始终配置在您的 application.properties 中,有点像这样:
I have been working with Spring boot for a bit now, and the datasource is always configured in your application.properties in every example I have seen, kind of like this:
# DataSource configuration
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/abcdef
spring.datasource.username=******
spring.datasource.password=******
但是,最近我一直在尝试集成 Spring Social,我看到的示例在 java 中的配置文件中配置它,如下所示:
However, lately I have been trying to integrate Spring Social, and the examples I have seen configure it in java in a config file like this:
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
return dataSource;
}
这允许数据源对象稍后被注入或自动连接到社交配置中,如此处.
This allows for the datasource object to later be injected or autowired into the social config as seen here for example.
我的问题是,我是否需要像这样配置一个数据源 bean 以便以后能够注入数据源,还是 Spring-boot 会为我处理?
My question is, do I need to configure a datasource bean like this to be able to later inject the datasource, or will Spring-boot handle that for me?
推荐答案
无论如何都不是 Spring(或 Boot)专家,但是如果属性存在并且有需求,Spring Boot 会自动提供一个 DataSource 类型的 Bean为它.要使用它,您只需 @Autowire
即可.
Not a Spring (or Boot) expert by any means, but Spring Boot will auto-provide a Bean of type DataSource if the properties are there and there's a requirement for it. To use it you just @Autowire
it.
这篇关于你如何在 Spring-boot 中自动装配/注入你的数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!