spring的注解开发@Component @Bean @Value @Autowired、@Qualifier @PropertySource @Configuration
spring的注解開發(fā)
啟動(dòng)注解功能
啟動(dòng)注解功能
 ? 啟動(dòng)注解掃描,加載類中配置的注解項(xiàng)
 
 ? 說明:
 ◆ 在進(jìn)行包所掃描時(shí),會(huì)對(duì)配置的包及其子包中所有文件進(jìn)行掃描
 ◆ 掃描過程是以文件夾遞歸迭代的形式進(jìn)行的
 ◆ 掃描過程僅讀取合法的java文件
 ◆ 掃描時(shí)僅讀取spring可識(shí)別的注解
 ◆ 掃描結(jié)束后會(huì)將可識(shí)別的有效注解轉(zhuǎn)化為spring對(duì)應(yīng)的資源加入IoC容器
 ? 注意:
 ◆ 無論是注解格式還是XML配置格式,最終都是將資源加載到IoC容器中,差別僅僅是數(shù)據(jù)讀取方式不同
 ◆ 從加載效率上來說注解優(yōu)于XML配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"> <!--注解只是一個(gè)標(biāo)記,如果spring不去掃描解析的話,這個(gè)標(biāo)記就不會(huì)生效--> <!-- 啟動(dòng)spring掃描注解的包,只掃描spring的注解--><context:component-scan base-package="com.fs"/></beans>將類交給springIOC管理,bean的定義@Component @Controller @Service @Repository
代碼解釋
package com.fs.demo; /* spring注解將類交給spring的ioc管理*/import org.springframework.stereotype.Component;/* @Component這個(gè)注解就相當(dāng)于核心配置文件中的<bean id="類名首字母小寫" class="權(quán)限定類名"/>@Component的衍生注解@Controller @Service @Repository,功能和 @Component一樣只是spring對(duì)應(yīng)三層結(jié)構(gòu)來定的注解,功能一樣,只是含義不同而已,所以使用其中那一個(gè)都可以將類交給ioc管理*/ @Component public class AnnotationDemo {public AnnotationDemo() {System.out.println("AnnotationDemo被spring的IOC管理了~~~");}public void testMethod(){System.out.println("測(cè)試方法執(zhí)行~~~");} }測(cè)試代碼
@Testpublic void testOne(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對(duì)象AnnotationDemo annotationDemo = (AnnotationDemo) applicationContext.getBean("annotationDemo");//使用類.class從ioc中獲取對(duì)象AnnotationDemo bean = applicationContext.getBean(AnnotationDemo.class);//調(diào)用方法annotationDemo.testMethod();bean.testMethod();}bean的作用域(@Scope(“單例或者雙列”))(了解)
bean的生命周期
@Bean注解的使用
代碼演示
package com.fs.demo;import com.alibaba.druid.pool.DruidDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;/* @Configuration放在類上,說明這個(gè)類是一個(gè)spring的配置類首先這個(gè)類要標(biāo)志是被spring掃描的,才會(huì)去掃描這個(gè)類下的其他注解@Bean*/ @Configuration public class DataSourceDemo {/*在方法上@Bean將方法的返回值交給ioc管理配置DruidDataSource鏈接池對(duì)象交給ioc管理*/@Bean("druidDataSource")//給一個(gè)idpublic DruidDataSource getDruidDataSource(){DruidDataSource druidDataSource = new DruidDataSource();druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");druidDataSource.setUrl("jdbc:mysql://192.168.93.132:3306/test");druidDataSource.setUsername("root");druidDataSource.setPassword("root");return druidDataSource;} }測(cè)試代碼
/*測(cè)試@Bean注入的druid連接池*/@Testpublic void testDataSource(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對(duì)象DruidDataSource druidDataSource = (DruidDataSource) applicationContext.getBean("druidDataSource"); // DataSource dataSource = (DataSource) applicationContext.getBean(DataSource.class);DruidDataSource dataSource = applicationContext.getBean(DruidDataSource.class); // System.out.println(dataSource);System.out.println(druidDataSource);}bean的屬性依耐注入DI
代碼演示@Value
package com.fs.pojo;import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; /* @Value非引用類型的屬性注入*/ @Component("student")//注入的時(shí)候起了個(gè)id名 //@Primary//沒有起id的時(shí)候,這個(gè)注解是讓這個(gè)bean優(yōu)先加載 public class Student {/*@ValueDI依耐注入,給基本類型屬性注入值*/@Value("18")private int age;@Value("小付")private String name;@Overridepublic String toString() {return "Student{" +"age=" + age +", name='" + name + '\'' +'}';} }代碼演示@Autowired、@Qualifier
package com.fs.pojo;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;/* 依耐注入之引用類型的注入@Autowired注意:注入的bean一定要在ioc容器中,才能注入因?yàn)檫@個(gè)注解是在ioc容器中去找對(duì)應(yīng)的bean注入*/ @Component public class Person{@Value("男")private String gender;/*@Autowired DI依耐注入按照類型自動(dòng)注入(id類名首字母小寫)*/ // @Autowired // private Student student;/*@Autowired@Qualifier("student")//若有相同類型的,按照id注入*/@Autowired@Qualifier("student")private Student student;@Overridepublic String toString() {return "Person{" +"gender='" + gender + '\'' +", student=" + student +'}';} }測(cè)試代碼
/*測(cè)試依耐注入屬性@Autowired@Qualifier("id")*/@Testpublic void testDI(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對(duì)象Person person = (Person) applicationContext.getBean("person");System.out.println(person);/*輸出結(jié)果:Person{gender='男', student=Student{age=18, name='小付'}}*/}了解注解
 
加載類路徑下的properties文件@PropertySource
準(zhǔn)備properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.93.132:3306/test jdbc.username=root jdbc.password=root代碼演示
package com.fs.properties;import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component;/* @PropertySource 引入類路徑下的的properties文件屬性:value = "classpath:resource中的properties文件"*/ @Component//將這個(gè)類交給ioc管理 @PropertySource(value = "classpath:jdbc.properties") public class PropertiesDemo {//@Value("${Key}")@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;@Overridepublic String toString() {return "PropertiesDemo{" +"driver='" + driver + '\'' +", url='" + url + '\'' +", username='" + username + '\'' +", password='" + password + '\'' +'}';} }測(cè)試代碼
/*測(cè)試@PropertySource(value = "classpath:jdbc.properties")測(cè)試引入類路徑下的properties文件*/@Testpublic void testProperties(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對(duì)象//PropertiesDemo propertiesDemo = (PropertiesDemo) applicationContext.getBean("propertiesDemo");//通過類名.classPropertiesDemo propertiesDemo = applicationContext.getBean(PropertiesDemo.class);System.out.println(propertiesDemo);//控制臺(tái)輸出結(jié)果: //PropertiesDemo{driver='com.mysql.jdbc.Driver', url='jdbc:mysql://192.168.93.132:3306/test', username='root', password='root'}}測(cè)底去除配置文件@Configuration、@ComponentScan @Import
我們現(xiàn)在還有applicationContext.xml這個(gè)文件,我們可以通過注解來指定一個(gè)配置類,從而讓配置文件不見
 
 @Import(類.class)配置類上寫入后,就會(huì)把你給的類存放在IOC容器中,存放的id為類的全限定類名(包名加加類名)
 
代碼演示
package com.fs.config;import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import;/* @Configuration這個(gè)注解就表示這是一個(gè)配置類 @ComponentScan("com.fs")這個(gè)注解表示spring掃描那些包下的注解 @Import({DataSourceConfig.class})寫在配置類,導(dǎo)入其他的配置類類.class就可以將這個(gè)類注入到spring的ioc容器中什么類都可以通過@Import({類.class,類2.class})來注入到spring的ioc容器中*/ @Configuration @ComponentScan("com.fs") @Import({DataSourceConfig.class}) public class SpringConfig { }測(cè)試代碼
//使用spring配置類來創(chuàng)建ioc@Testpublic void testSpringConfig(){//創(chuàng)建ioc容器 AnnotationConfigApplicationContext(配置類.class)ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);//通過類名首字母小寫從ioc中獲取對(duì)象//PropertiesDemo propertiesDemo = (PropertiesDemo) applicationContext.getBean("propertiesDemo");//通過類名.classPropertiesDemo propertiesDemo = applicationContext.getBean(PropertiesDemo.class);System.out.println(propertiesDemo);}/*測(cè)試@Import 導(dǎo)入的druid連接池*/@Testpublic void testImport(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對(duì)象DruidDataSource druidDataSource = (DruidDataSource) applicationContext.getBean("druidDataSource"); // DataSource dataSource = (DataSource) applicationContext.getBean(DataSource.class);DruidDataSource dataSource = applicationContext.getBean(DruidDataSource.class); // System.out.println(dataSource);System.out.println(druidDataSource);}依耐加載
 
 
 依賴加載應(yīng)用場(chǎng)景
 ? @DependsOn
 ◆微信訂閱號(hào),發(fā)布消息和訂閱消息的bean的加載順序控制
 ◆雙11活動(dòng)期間,零點(diǎn)前是結(jié)算策略A,零點(diǎn)后是結(jié)算策略B,策略B操作的數(shù)據(jù)為促銷數(shù)據(jù)。策略B
 加載順序與促銷數(shù)據(jù)的加載順序
 ? @Lazy
 ◆程序?yàn)?zāi)難出現(xiàn)后對(duì)應(yīng)的應(yīng)急預(yù)案處理是啟動(dòng)容器時(shí)加載時(shí)機(jī)
 ? @Order
 ◆多個(gè)種類的配置出現(xiàn)后,優(yōu)先加載系統(tǒng)級(jí)的,然后加載業(yè)務(wù)級(jí)的,避免細(xì)粒度的加載控制
總結(jié)
以上是生活随笔為你收集整理的spring的注解开发@Component @Bean @Value @Autowired、@Qualifier @PropertySource @Configuration的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Mybatis与Spring整合之配置文
 - 下一篇: Spring整合Mybatis之注解方式