@Configuration和 @Bean 的基本使用(包含@ComponentScan 和 PropertySource)

1、 @Configuration 和 @ Bean 注解的使用

情景一:

//声明当前是一个配置文件类,相当于 xml文件
@Configuration
public class MyConfig {

    //这个注解的目的是创建一个对象,所以该方法一定要有返回值,不然spring内部调用这个方法的时候没哟返回值,无法获得对象
    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///db_shopping");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;

    }
}

上面相当于创建了一个xml配置文件,在类中创建了DataSource 对象呢
编写测试类

public class Springboot_Annotation_Test {

    @Test
    public void test1(){
        //加载测试类,相当于以前的加载xml配置文件
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        DataSource dataSource = context.getBean(DataSource.class);
        System.out.println(dataSource);


    }

}

测试结果:

D:\JDK1.8\Java\jdk1.8.0_131\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:E:\idea\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar=61182:E:\idea\IntelliJ IDEA 2018.2.4\bin" -Dfile.encoding=UTF-8 -classpath "E:\idea\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar;E:\idea\IntelliJ IDEA 2018.2.4\plugins\junit\lib\junit-rt.jar;E:\idea\IntelliJ IDEA 2018.2.4\plugins\junit\lib\junit5-rt.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\charsets.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\deploy.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\javaws.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jce.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jfr.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jsse.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\management-agent.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\plugin.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\resources.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\rt.jar;D:\idea\idea-workspace\springboot2\springboot_annotation\target\test-classes;D:\idea\idea-workspace\springboot2\springboot_annotation\target\classes;D:\my_maven_local_repository\org\springframework\spring-webmvc\5.0.8.RELEASE\spring-webmvc-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-aop\5.0.8.RELEASE\spring-aop-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-beans\5.0.8.RELEASE\spring-beans-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-context\5.0.8.RELEASE\spring-context-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-core\5.0.8.RELEASE\spring-core-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-jcl\5.0.8.RELEASE\spring-jcl-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-expression\5.0.8.RELEASE\spring-expression-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-web\5.0.8.RELEASE\spring-web-5.0.8.RELEASE.jar;D:\my_maven_local_repository\com\alibaba\druid\1.1.10\druid-1.1.10.jar;D:\my_maven_local_repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;D:\my_maven_local_repository\org\springframework\spring-jdbc\5.0.8.RELEASE\spring-jdbc-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-tx\5.0.8.RELEASE\spring-tx-5.0.8.RELEASE.jar;D:\my_maven_local_repository\junit\junit\4.12\junit-4.12.jar;D:\my_maven_local_repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 Springboot_Annotation_Test,test2
十月 24, 2018 5:37:05 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1bc6a36e: startup date [Wed Oct 24 17:37:05 CST 2018]; root of context hierarchy
{
	CreateTime:"2018-10-24 17:37:07",
	ActiveCount:0,
	PoolingCount:0,
	CreateCount:0,
	DestroyCount:0,
	CloseCount:0,
	ConnectCount:0,
	Connections:[
	]
}

Process finished with exit code 0

情景二:
如果在测试类中含有多个方法的返回值是一样的,可以才用别名的方式解决问题

    @Bean("method1")
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///db_shopping");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;

    }

    @Bean("method2")//相当于<bean id = "method2">
    public DataSource getDataSource2(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///p2p");
        dataSource.setUsername("root");
        dataSource.setPassword("qishimeiyoumima");
        return dataSource;

}

测试类

    @Test
    public void test2(){
        //加载测试类,相当于以前的加载xml配置文件
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        DataSource dataSource = (DataSource) context.getBean("method2");
        System.out.println(dataSource);

    }

测试结果如情景一

情景三:
如果测试类中一个方法需要另一方法的返回值,或者说是需要另一个类的对象
方法一:
配置类

	//创建平台事物管理器
    @Bean
    public PlatformTransactionManager getPlatformTranscationManager(){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(getDataSource());//直接使用返回对象的方法名
        return transactionManager;

    }

测试类

    @Test
    public void test3(){
        //加载测试类,相当于以前的加载xml配置文件
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        PlatformTransactionManager contextBean = context.getBean(PlatformTransactionManager.class);
        System.out.println(contextBean);

    }

测试结果

D:\JDK1.8\Java\jdk1.8.0_131\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:E:\idea\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar=61386:E:\idea\IntelliJ IDEA 2018.2.4\bin" -Dfile.encoding=UTF-8 -classpath "E:\idea\IntelliJ IDEA 2018.2.4\lib\idea_rt.jar;E:\idea\IntelliJ IDEA 2018.2.4\plugins\junit\lib\junit-rt.jar;E:\idea\IntelliJ IDEA 2018.2.4\plugins\junit\lib\junit5-rt.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\charsets.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\deploy.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\javaws.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jce.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jfr.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\jsse.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\management-agent.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\plugin.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\resources.jar;D:\JDK1.8\Java\jdk1.8.0_131\jre\lib\rt.jar;D:\idea\idea-workspace\springboot2\springboot_annotation\target\test-classes;D:\idea\idea-workspace\springboot2\springboot_annotation\target\classes;D:\my_maven_local_repository\org\springframework\spring-webmvc\5.0.8.RELEASE\spring-webmvc-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-aop\5.0.8.RELEASE\spring-aop-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-beans\5.0.8.RELEASE\spring-beans-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-context\5.0.8.RELEASE\spring-context-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-core\5.0.8.RELEASE\spring-core-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-jcl\5.0.8.RELEASE\spring-jcl-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-expression\5.0.8.RELEASE\spring-expression-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-web\5.0.8.RELEASE\spring-web-5.0.8.RELEASE.jar;D:\my_maven_local_repository\com\alibaba\druid\1.1.10\druid-1.1.10.jar;D:\my_maven_local_repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;D:\my_maven_local_repository\org\springframework\spring-jdbc\5.0.8.RELEASE\spring-jdbc-5.0.8.RELEASE.jar;D:\my_maven_local_repository\org\springframework\spring-tx\5.0.8.RELEASE\spring-tx-5.0.8.RELEASE.jar;D:\my_maven_local_repository\junit\junit\4.12\junit-4.12.jar;D:\my_maven_local_repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit4 Springboot_Annotation_Test,test3
十月 24, 2018 5:50:24 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1bc6a36e: startup date [Wed Oct 24 17:50:24 CST 2018]; root of context hierarchy
org.springframework.jdbc.datasource.DataSourceTransactionManager@5e82df6a

Process finished with exit code 0

方法二:
使用自动注入的方式

@Configuration
public class MyConfig {

    @Autowired
    @Qualifier("method1")
    private DataSource dataSource;

    //这个注解的目的是创建一个对象,所以该方法一定要有返回值,不然spring内部调用这个方法的时候没哟返回值,无法获得对象
    @Bean("method1")
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///db_shopping");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;

    }

    @Bean("method4")
    public PlatformTransactionManager getPlatformTranscationManager2(){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;

    }

测试类

    @Test
    public void test4(){
        //加载测试类,相当于以前的加载xml配置文件
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        PlatformTransactionManager contextBean = (PlatformTransactionManager) context.getBean("method4");
        System.out.println(contextBean);

    }

测试结果和方法一相同

情景四:
如果配置类中的方法需要传入参数


    @Bean("method5")
    public PlatformTransactionManager getPlatformTranscationManager3(DataSource method1){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(method1);
        return transactionManager;

    }

则传入参数的名字需要注意:如果方法需要参数,可以直接要求注入参数过来,如果注入的参数在spring中只有一个值,可以随便写形参名字,如果这个参数对象类型在spring中有多个值,那么形参的名字应该是对象的名字 ,比如bean注解中的name值或者是被bean修饰的方法的方法名

情景五:
如果在另一个包中有一个UserServiceImpl 类,需要创建一个他的实例

import com.qf.springboot.annotation.user.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Override
    public void show() {
        System.out.println("hello world");
    }
}

配置文件类

//声明当前是一个配置文件类,相当于 xml文件
@Configuration
//相当于xml文件中的 <context:component-scan base-package="com.qianfeng.springboot"/>
@ComponentScan("com.qf.springboot.annotation.user.service")
public class MyConfig {
下面的省略......

测试类

    @Test
    public void test5(){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        UserService userService = context.getBean(UserService.class);
        userService.show();
    }

测试结果

信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1bc6a36e: startup date [Wed Oct 24 19:07:15 CST 2018]; root of context hierarchy
hello world //结果正确

Process finished with exit code 0

情景六:使用@PropertySource()注解

配置文件类

//声明当前是一个配置文件类,相当于 xml文件
@Configuration
//相当于xml文件中的 <context:component-scan base-package="com.qianfeng.springboot"/>
@ComponentScan("com.qf.springboot.annotation.user.service")
//相当于取代了xml中的<context:property-placeholder location="classpath:db.properties"/>
@PropertySource(value = {"db.properties"})
public class MyConfig {

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.driver}")
    private String driver;

    @Bean("abcd") //abc相当于我们在 <bean id="abc">
    public DataSource getDataSource3() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;

    }
下面的省略......

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值