1、创建一个SpringConfig配置类。添加注解@Configuration
2、定义一个方法获得要管理的对象
3、添加@Bean,表示当前方法的返回值是一个bean
- @Configuration
- public class SpringConfig {
-
- //1、定义一个方法获得要管理的对象
- //2、添加@Bean,表示当前方法的返回值是一个bean
- @Bean
- public DataSource dataSource(){
- DruidDataSource dataSource = new DruidDataSource();
- dataSource.setDriverClassName("123");
- dataSource.setUrl("123");
- dataSource.setUsername("123");
- dataSource.setPassword("123");
- return dataSource;
- }
- }
4、打印获取到的对象
- public class App {
- public static void main(String[] args) {
- AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
- DataSource dataSource = ctx.getBean(DataSource.class);
- System.out.println(dataSource);
- }
- }
5、打印结果
{
CreateTime:"2022-07-20 13:41:44",
ActiveCount:0,
PoolingCount:0,
CreateCount:0,
DestroyCount:0,
CloseCount:0,
ConnectCount:0,
Connections:[
]
}
6、或者创建一个JdbcConfig配置类,
使用@Value注入
- @Configuration
- @PropertySource("classpath:jdbc.properties")
- @Import(JdbcConfig.class)
- public class SpringConfig {
-
- }
-
-
-
-
-
-
- public class JdbcConfig {
-
- @Value("${jdbc.driver}")
- private String driver;
- @Value("${jdbc.url}")
- private String url;
- @Value("${jdbc.username}")
- private String username;
- @Value("${jdbc.password}")
- private String password;
-
- @Bean
- public DataSource dataSource(){
- DruidDataSource dataSource = new DruidDataSource();
- System.out.println(driver);
- System.out.println(url);
- System.out.println(username);
- System.out.println(password);
- dataSource.setDriverClassName(driver);
- dataSource.setUrl(url);
- dataSource.setUsername(username);
- dataSource.setPassword(password);
- return dataSource;
- }
- }
-
根据类型自动装配
注意点:SpringConfig要使用注解@ComponentScan 扫描定义Bean的包
- public class JdbcConfig {
-
- @Value("${jdbc.driver}")
- private String driver;
- @Value("${jdbc.url}")
- private String url;
- @Value("${jdbc.username}")
- private String username;
- @Value("${jdbc.password}")
- private String password;
-
- @Bean
- public DataSource dataSource(BookDao bookDao){
- System.out.println(bookDao);
- DruidDataSource dataSource = new DruidDataSource();
- System.out.println(driver);
- System.out.println(url);
- System.out.println(username);
- System.out.println(password);
- dataSource.setDriverClassName(driver);
- dataSource.setUrl(url);
- dataSource.setUsername(username);
- dataSource.setPassword(password);
- return dataSource;
- }
- }
-
- @Repository
- public class BookDaoImpl implements BookDao {
-
- public void save() {
- System.out.println("book dao save...");
- }
-
- }
-
-
- @Configuration
- @PropertySource("classpath:jdbc.properties")
- @ComponentScan("com.hyk.dao")
- @Import(JdbcConfig.class)
- public class SpringConfig {
-
- }
-