注解 @Configuration 和 @Bean

时间:2022-10-09 09:06:56 类型:JAVA
字号:    

1、注解 @Configuration 和 @Bean

新建一个类,但是我不用 @Service 注解,也就是说,它是个普通的类,那么我们如何使它也成为一个 Bean 让 Spring 去管理呢?只需要 @Configuration 和 @Bean 两个注解即可,如下:

@Configuration
public class JavaConfig {
    @Bean
    public TestService getTestService() {
        return new TestService();
    }
}

@Configuration 表示该类是个配置类, @Bean 表示该方法返回一个 Bean。

这样就把 TestService 作为 Bean 让 Spring 去管理了,在其他地方,我们如果需要使用该 Bean,和原来一样,直接使用

@Resource 注解注入进来即可使用,非常方便。

@Resource
private TestService testService;

  2、读取外部的配置文件

  数据库连接信息 db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/data0917?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

配置类:

@Configuration
@PropertySource(value= {"classpath:db.properties", "xxx"},ignoreResourceNotFound=true)
public class DBConfig {

    @Value("${db.url}")    private String url;
    @Value("${db.driverClassName}")    private String driverClassName;
    @Value("${db.username}")    private String username;
    @Value("${db.password}")    private String password;
    
    public void dataSource () {
        System.out.println("======url=" + url);
        System.out.println(driverClassName);
    }
}


<