spring的注解开发@Component @Bean @Value @Autowired、@Qualifier @PropertySource @Configuration
spring的注解開發(fā)
啟動注解功能
啟動注解功能
⚫ 啟動注解掃描,加載類中配置的注解項
⚫ 說明:
◆ 在進行包所掃描時,會對配置的包及其子包中所有文件進行掃描
◆ 掃描過程是以文件夾遞歸迭代的形式進行的
◆ 掃描過程僅讀取合法的java文件
◆ 掃描時僅讀取spring可識別的注解
◆ 掃描結(jié)束后會將可識別的有效注解轉(zhuǎn)化為spring對應(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">
<!--注解只是一個標(biāo)記,如果spring不去掃描解析的話,這個標(biāo)記就不會生效-->
<!-- 啟動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這個注解就相當(dāng)于核心配置文件中的<bean id="類名首字母小寫" class="權(quán)限定類名"/>@Component的衍生注解@Controller @Service @Repository,功能和 @Component一樣只是spring對應(yīng)三層結(jié)構(gòu)來定的注解,功能一樣,只是含義不同而已,所以使用其中那一個都可以將類交給ioc管理*/
@Component
public class AnnotationDemo {public AnnotationDemo() {System.out.println("AnnotationDemo被spring的IOC管理了~~~");}public void testMethod(){System.out.println("測試方法執(zhí)行~~~");}
}
測試代碼
@Testpublic void testOne(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對象AnnotationDemo annotationDemo = (AnnotationDemo) applicationContext.getBean("annotationDemo");//使用類.class從ioc中獲取對象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放在類上,說明這個類是一個spring的配置類首先這個類要標(biāo)志是被spring掃描的,才會去掃描這個類下的其他注解@Bean*/
@Configuration
public class DataSourceDemo {/*在方法上@Bean將方法的返回值交給ioc管理配置DruidDataSource鏈接池對象交給ioc管理*/@Bean("druidDataSource")//給一個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;}
}
測試代碼
/*測試@Bean注入的druid連接池*/@Testpublic void testDataSource(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對象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")//注入的時候起了個id名
//@Primary//沒有起id的時候,這個注解是讓這個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容器中,才能注入因為這個注解是在ioc容器中去找對應(yīng)的bean注入*/
@Component
public class Person{@Value("男")private String gender;/*@Autowired DI依耐注入按照類型自動注入(id類名首字母小寫)*/
// @Autowired
// private Student student;/*@Autowired@Qualifier("student")//若有相同類型的,按照id注入*/@Autowired@Qualifier("student")private Student student;@Overridepublic String toString() {return "Person{" +"gender='" + gender + '\'' +", student=" + student +'}';}
}
測試代碼
/*測試依耐注入屬性@Autowired@Qualifier("id")*/@Testpublic void testDI(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對象Person person = (Person) applicationContext.getBean("person");System.out.println(person);/*輸出結(jié)果:Person{gender='男', student=Student{age=18, name='小付'}}*/}
了解注解
加載類路徑下的properties文件@PropertySource
準備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//將這個類交給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 + '\'' +'}';}
}
測試代碼
/*測試@PropertySource(value = "classpath:jdbc.properties")測試引入類路徑下的properties文件*/@Testpublic void testProperties(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對象//PropertiesDemo propertiesDemo = (PropertiesDemo) applicationContext.getBean("propertiesDemo");//通過類名.classPropertiesDemo propertiesDemo = applicationContext.getBean(PropertiesDemo.class);System.out.println(propertiesDemo);//控制臺輸出結(jié)果:
//PropertiesDemo{driver='com.mysql.jdbc.Driver', url='jdbc:mysql://192.168.93.132:3306/test', username='root', password='root'}}
測底去除配置文件@Configuration、@ComponentScan @Import
我們現(xiàn)在還有applicationContext.xml這個文件,我們可以通過注解來指定一個配置類,從而讓配置文件不見
@Import(類.class)配置類上寫入后,就會把你給的類存放在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這個注解就表示這是一個配置類
@ComponentScan("com.fs")這個注解表示spring掃描那些包下的注解
@Import({DataSourceConfig.class})寫在配置類,導(dǎo)入其他的配置類類.class就可以將這個類注入到spring的ioc容器中什么類都可以通過@Import({類.class,類2.class})來注入到spring的ioc容器中*/
@Configuration
@ComponentScan("com.fs")
@Import({DataSourceConfig.class})
public class SpringConfig {
}
測試代碼
//使用spring配置類來創(chuàng)建ioc@Testpublic void testSpringConfig(){//創(chuàng)建ioc容器 AnnotationConfigApplicationContext(配置類.class)ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);//通過類名首字母小寫從ioc中獲取對象//PropertiesDemo propertiesDemo = (PropertiesDemo) applicationContext.getBean("propertiesDemo");//通過類名.classPropertiesDemo propertiesDemo = applicationContext.getBean(PropertiesDemo.class);System.out.println(propertiesDemo);}/*測試@Import 導(dǎo)入的druid連接池*/@Testpublic void testImport(){//創(chuàng)建ioc容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//通過類名首字母小寫從ioc中獲取對象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)用場景
⚫ @DependsOn
◆微信訂閱號,發(fā)布消息和訂閱消息的bean的加載順序控制
◆雙11活動期間,零點前是結(jié)算策略A,零點后是結(jié)算策略B,策略B操作的數(shù)據(jù)為促銷數(shù)據(jù)。策略B
加載順序與促銷數(shù)據(jù)的加載順序
⚫ @Lazy
◆程序災(zāi)難出現(xiàn)后對應(yīng)的應(yīng)急預(yù)案處理是啟動容器時加載時機
⚫ @Order
◆多個種類的配置出現(xiàn)后,優(yōu)先加載系統(tǒng)級的,然后加載業(yè)務(wù)級的,避免細粒度的加載控制
總結(jié)
以上是生活随笔為你收集整理的spring的注解开发@Component @Bean @Value @Autowired、@Qualifier @PropertySource @Configuration的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 王者荣耀芈月技能怎么连招
- 下一篇: Codeforces Round #21