Spring常用注解(絕對經(jīng)典)
1、需要導(dǎo)入的spring框架的依賴
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
2、@Configuration
設(shè)置類為配置類
3、AnnotationConfigApplicationContext
- 通過配置類獲取上下文環(huán)境applicationContext
- 可以通過getBeanDefinitionNames()獲得配置類中配置的各類Bean
- 也可以使用getBeanNamesForType()通過類型來獲得bean的name(id)
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String str : beanDefinitionNames) {
System.out.println(str);
}
4、@Bean
- 注冊一個(gè)javaBean
- 默認(rèn)用方法名作為Bean的id
- 使用AnnotationConfigApplicationContext的實(shí)例 通過getBean來獲得這個(gè)Bean
@Configuration
@ComponentScan(value = "com.atguigu")
public class MainConfig {
@Bean
public Person person(){
return new Person("lisi",20);
}
}
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
5、@ComponentScan
為配置類開啟組件掃描
- 放在配置類的上方,指定掃描的包路徑如
@ComponentScan(value = "com.atguigu")
- 還可以使用excludeFilter來設(shè)置類掃描規(guī)則如包含、排除,excludeFilter需要設(shè)置為一個(gè)數(shù)組
排除
包含使用excludeFilter,并為其設(shè)置一個(gè)過濾數(shù)組,來指定需要過濾掉那些組件
@Configuration
@ComponentScan(value = "com.atguigu",excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
classes ={Controller.class,Service.class} )
})
public class MainConfig {
@Bean
public Person person(){
return new Person("lisi",20);
}
}
包含
包含使用includeFilter,包含里面需要設(shè)置使用默認(rèn)規(guī)則為false
@Configuration
@ComponentScan(value = "com.atguigu",includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
classes ={Controller.class,Service.class} )},useDefaultFilters = false)
public class MainConfig {
@Bean
public Person person(){
return new Person("lisi",20);
}
}
還可以設(shè)置按給定類型過濾
@Configuration
@ComponentScan(value = "com.atguigu",includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,
classes ={Controller.class,Service.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
classes ={BookService.class})
},useDefaultFilters = false)
public class MainConfig {
@Bean
public Person person(){
return new Person("lisi",20);
}
}
其他可以設(shè)置的過濾方式還可以有:
- 使用FilterType.ASPECTJ按照ASPECTJ表達(dá)式
- 使用FilterType.REGEX按照REGEX正則表達(dá)式
- 使用FilterType.CUSTOM按照自定義規(guī)則過濾(需要實(shí)現(xiàn)TypeFilter接口)
自定義過濾規(guī)則
public class MyTypeFilter implements TypeFilter {
/*
metadataReader:讀取到的當(dāng)前正在掃描的類的信息
metadataReaderFactory:可以獲取到其他任何類的信息
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//獲取當(dāng)前類的注解信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//獲取當(dāng)前正在掃描的類的類信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//獲取當(dāng)前類的資源(類的路徑)
Resource resource = metadataReader.getResource();
String className = classMetadata.getClassName();
System.out.println(resource);
System.out.println(className);
if(className.contains("er")){
return true;
}
return false;
}
}
設(shè)置自定義規(guī)則
@Configuration
@ComponentScan(value = "com.atguigu",includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,
classes = {MyTypeFilter.class})
},useDefaultFilters = false)
public class MainConfig {
@Bean
public Person person(){
return new Person("lisi",20);
}
}
測試代碼
@Test
public void testbeans() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String str : beanDefinitionNames) {
System.out.println(str);
}
}
測試結(jié)果
測試規(guī)則打印內(nèi)容
file [/Users/human/Desktop/Project/05SpringMVC/spring-annotation/target/classes/com/atguigu/bean/Person.class]
com.atguigu.bean.Person
file [/Users/human/Desktop/Project/05SpringMVC/spring-annotation/target/classes/com/atguigu/config/MyTypeFilter.class]
com.atguigu.config.MyTypeFilter
file [/Users/human/Desktop/Project/05SpringMVC/spring-annotation/target/classes/com/atguigu/controller/BookController.class]
com.atguigu.controller.BookController
file [/Users/human/Desktop/Project/05SpringMVC/spring-annotation/target/classes/com/atguigu/dao/BookDAO.class]
com.atguigu.dao.BookDAO
file [/Users/human/Desktop/Project/05SpringMVC/spring-annotation/target/classes/com/atguigu/service/BookService.class]
com.atguigu.service.BookService
file [/Users/human/Desktop/Project/05SpringMVC/spring-annotation/target/classes/com/atguigu/test/MainTest.class]
com.atguigu.test.MainTest
測試類打印過濾結(jié)果
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
person
myTypeFilter
bookController
bookService
6、@Controller
將類配置為Controller類
7、@Service
將類配置為service類
8、@Repository
將類配置為dao操作的類
9、@Component
將類配置為通用類組件
10、@Scope
調(diào)整bean的作用域范圍,默認(rèn)單實(shí)例,可以修改為多實(shí)例
Bean是默認(rèn)單實(shí)例的,通過指明prototype(多實(shí)例)和singleton(單實(shí)例)屬性指明是否單實(shí)例
- prototype:多實(shí)例
- singleton:單實(shí)例
- request:同一次請求創(chuàng)建一個(gè)實(shí)例
- session:同一個(gè)session創(chuàng)建一個(gè)實(shí)例
@Configuration
@ComponentScan(value = "com.atguigu")
public class MainConfig {
//Bean是默認(rèn)單實(shí)例的,通過指明prototype(多實(shí)例)和singleton(單實(shí)例)屬性指明是是否單實(shí)例
//prototype:多實(shí)例
//singleton:單實(shí)例
//request:同一次請求創(chuàng)建一個(gè)實(shí)例
//session:同一個(gè)session創(chuàng)建一個(gè)實(shí)例
@Scope("prototype")
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
}
測試
@Test
public void testbeans() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Object bean1 = applicationContext.getBean("person");
Object bean2 = applicationContext.getBean("person");
System.out.println(bean1==bean2);
}
測試結(jié)果為false
11、@Lazy懶加載
實(shí)例默認(rèn)在容器創(chuàng)建時(shí)立即加載
使用@Lazy后,當(dāng)需要?jiǎng)?chuàng)建實(shí)例時(shí)才被加載
-
不使用懶加載
實(shí)體類構(gòu)造函數(shù)
public Person(String name, Integer age) {
System.out.println("給容器添加Person對象");
this.name = name;
this.age = age;
}
測試代碼
@Test
public void testbeans() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println("容器已創(chuàng)建完成");
//沒有獲取類的代碼,單實(shí)際上類的實(shí)例已經(jīng)被加載進(jìn)容器了
}
測試結(jié)果
給容器添加Person對象
容器已創(chuàng)建完成
- 使用懶加載
@Configuration
@ComponentScan(value = "com.atguigu")
public class MainConfig {
// @Scope("prototype")
@Lazy
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
}
測試代碼
@Test
public void testbeans() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println("容器已創(chuàng)建完成");
Object bean1 = applicationContext.getBean("person");//這一句出現(xiàn)后才加載Person類
}
測試結(jié)果
給容器添加Person對象
容器已創(chuàng)建完成
12、@Conditional
- 按一定條件注冊bean,滿足條件就給容器注冊bean,否則不注入
- 要作為自定義條件,需要?jiǎng)?chuàng)建自定義condition類,并要實(shí)現(xiàn)Condition接口,并實(shí)現(xiàn)match方法
- conditional不僅可以標(biāo)在方法上,還可以標(biāo)記在類上
//判斷是否是Linux系統(tǒng)的條件
//要作為自定義條件,要實(shí)現(xiàn)Condition接口,并實(shí)現(xiàn)match方法
//AnnotatedTypeMetadata:注釋信息
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//判斷l(xiāng)inux洗洗
ConfigurableListableBeanFactory beanFactory = conditionContext.getBeanFactory();
//獲取類加載器
ClassLoader classLoader = conditionContext.getClassLoader();
//獲得當(dāng)前環(huán)境信息
Environment environment = conditionContext.getEnvironment();
//獲取到bean定義的注冊類
BeanDefinitionRegistry registry = conditionContext.getRegistry();
String OSproperty = environment.getProperty("os.name");
if (OSproperty.contains("Mac OS X")){
return true;
}
return false;
}
}
另一個(gè)自定義條件
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Environment environment = conditionContext.getEnvironment();
//獲取操作系統(tǒng)信息
String OSproperty = environment.getProperty("os.name");
if (OSproperty.contains("Window")){
return true;
}
return false;
}
}
配置類信息
@Configuration
@ComponentScan(value = "com.atguigu")
public class MainConfig {
// @Scope("prototype")
@Lazy
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
@Conditional({WindowsCondition.class})
@Bean("male")
public Person personMale(){
return new Person("lisi",33);
}
@Conditional({LinuxCondition.class})
@Bean("female")
public Person personFemale(){
return new Person("wanger",23);
}
}
測試類信息
@Test
public void testBeans() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
//獲取ioc容器的運(yùn)行環(huán)境
ConfigurableEnvironment environment=applicationContext.getEnvironment();
//獲取操作系統(tǒng)名稱
String property = environment.getProperty("os.name");
System.out.println(property);
String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
for (String name:namesForType) {
System.out.println(name);
}
}
測試結(jié)果
Mac OS X
person
female
13、給IOC容器中注冊組件的5種方法
- 包掃描+組件類上標(biāo)注注解:(@Controller,@Service,@Repository,@Component)
- @Bean:導(dǎo)入第三方包的組件
- @Import:快速給容器導(dǎo)入一個(gè)組件
1)@Import(要導(dǎo)入到容器的組件),容器中就會(huì)自動(dòng)注冊這個(gè)逐漸,id默認(rèn)是全類名
2)ImportSelector:返回需要導(dǎo)入的組件的全類名數(shù)組
4.使用ImportBeanDefinitionRegistrar
5.使用Spring提供的FactoryBean(工廠bean)注冊組件
1)默認(rèn)獲得的是工廠bean調(diào)用getObject創(chuàng)建的對象
2)要獲取工廠bean本身,需要給id前面加一個(gè)&標(biāo)識
14、@Import 快速導(dǎo)入一個(gè)類
使用@Import快速為配置類導(dǎo)入一個(gè)bean類
可以同時(shí)導(dǎo)入多個(gè)bean類
需要再配置類上方書寫
- 創(chuàng)建被導(dǎo)入的bean類
public class Color {
}
public class Red {
}
- 給配置類導(dǎo)入該類
@Configuration
@ComponentScan(value = "com.atguigu")
@Import({Color.class, Red.class})//在這里進(jìn)行快速地導(dǎo)入,可以是數(shù)組形式
public class MainConfig {
// @Scope("prototype")
@Lazy
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
@Conditional({WindowsCondition.class})
@Bean("male")
public Person personMale(){
return new Person("lisi",33);
}
@Conditional({LinuxCondition.class})
@Bean("female")
public Person personFemale(){
return new Person("wanger",23);
}
}
測試類代碼
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
@Test
public void testImport(){
printBeans(applicationContext);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name:beanDefinitionNames) {
System.out.println(name);
}
}
測試結(jié)果
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookDAO
bookService
com.atguigu.bean.Color
com.atguigu.bean.Red
person
female
15、ImportSelector接口導(dǎo)入一個(gè)類
- ImportSelector:返回需要導(dǎo)入的組件的全類名數(shù)組
- 需要實(shí)現(xiàn)ImportSelector接口并改寫selectImports方法
創(chuàng)建需要被導(dǎo)入的類
public class Blue {
}
public class Yellow {
}
創(chuàng)建自己的Import類
public class MyImportSelect implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
//返回值是要導(dǎo)入到容器中的組件全類名
//annotationMetadata:注解信息
return new String[]{"com.atguigu.bean.Blue", "com.atguigu.bean.Yellow"};
}
}
在配置類中設(shè)置@Import導(dǎo)入的自定義類選擇器
注意:@Import({Color.class, Red.class,MyImportSelect.class})
@Configuration
@ComponentScan(value = "com.atguigu")
@Import({Color.class, Red.class,MyImportSelect.class})
public class MainConfig {
// @Scope("prototype")
@Lazy
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
@Conditional({WindowsCondition.class})
@Bean("male")
public Person personMale(){
return new Person("lisi",33);
}
@Conditional({LinuxCondition.class})
@Bean("female")
public Person personFemale(){
return new Person("wanger",23);
}
}
測試代碼
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
@Test
public void testImport(){
printBeans(applicationContext);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name:beanDefinitionNames) {
System.out.println(name);
}
}
測試結(jié)果
Color,Red,Blue,Yellow都有了
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookDAO
bookService
com.atguigu.bean.Color
com.atguigu.bean.Red
com.atguigu.bean.Blue
com.atguigu.bean.Yellow
person
female
16、使用ImportBeanDefinitionRegistrar接口導(dǎo)入類
自定義導(dǎo)入的類定義,需要實(shí)現(xiàn)ImportBeanDefinitionRegistrar接口,并重寫 registerBeanDefinitions方法
創(chuàng)建一個(gè)需要被注入的類
public class RainBow {
}
創(chuàng)建自定義的注冊類信息類
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
//annotationMetadata:當(dāng)前類的注解信息
//beanDefinitionRegistry:beanDefinition注冊類
//把所有需要添加到容器中的bean,調(diào)用beanDefinitionRegistry.registerBeanDefinition手動(dòng)注冊類
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
boolean red = beanDefinitionRegistry.containsBeanDefinition("com.atguigu.bean.Red");//判斷定義中是否有紅色
boolean blue = beanDefinitionRegistry.containsBeanDefinition("com.atguigu.bean.Blue");//判斷定義中是否有藍(lán)色
if(red && blue){
//指定bean名
RootBeanDefinition rainbowDefinition = new RootBeanDefinition(RainBow.class);
//注冊了一個(gè)bean,并指定了一個(gè)類名(別名)
beanDefinitionRegistry.registerBeanDefinition("rainbow", rainbowDefinition);
}
}
}
在配置類中進(jìn)行配置
注意:@Import({Color.class, Red.class,MyImportSelect.class,MyImportBeanDefinitionRegistrar.class})
@Configuration
@ComponentScan(value = "com.atguigu")
@Import({Color.class, Red.class,MyImportSelect.class,MyImportBeanDefinitionRegistrar.class})
public class MainConfig {
// @Scope("prototype")
@Lazy
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
@Conditional({WindowsCondition.class})
@Bean("male")
public Person personMale(){
return new Person("lisi",33);
}
@Conditional({LinuxCondition.class})
@Bean("female")
public Person personFemale(){
return new Person("wanger",23);
}
}
測試類
@Test
public void testImport(){
printBeans(applicationContext);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name:beanDefinitionNames) {
System.out.println(name);
}
}
測試結(jié)果
顯示了rainbow
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookDAO
bookService
com.atguigu.bean.Color
com.atguigu.bean.Red
com.atguigu.bean.Blue
com.atguigu.bean.Yellow
person
female
rainbow
17、使用FactoryBean接口導(dǎo)入類
創(chuàng)建自定義工廠類,實(shí)現(xiàn)FactoryBean接口,并改寫一下方法
getObject() //返回工廠生產(chǎn)的類對象
getObjectType()//返回工廠生產(chǎn)的類類型
isSingleton() //返回單例
創(chuàng)建自定義工廠類
這里實(shí)現(xiàn)FactoryBean接口,實(shí)現(xiàn)三個(gè)方法,注意泛型中使用Color類
public class ColorFactory implements FactoryBean<Color> {
//返回一個(gè)Color對象,這個(gè)對象會(huì)添加到容器中
@Override
public Color getObject() throws Exception {
System.out.println("color factory generate a instance");
return new Color();
}
@Override
public Class<?> getObjectType() {
return Color.class;
}
@Override
public boolean isSingleton() {
//true:返回單例,在容器中保存一份
//false:返回多份類實(shí)例,每次獲取工廠bean都會(huì)創(chuàng)建一個(gè)新的對象
return false;
}
}
在配置類中定義這個(gè)類組件
注意:
@Bean
public ColorFactory colorFactoryBean(){
return new ColorFactory();
}
}
@Configuration
@ComponentScan(value = "com.atguigu")
@Import({Color.class, Red.class,MyImportSelect.class,MyImportBeanDefinitionRegistrar.class})
public class MainConfig {
// @Scope("prototype")
@Lazy
@Bean("person")//指定bean的自定義id
public Person person(){
return new Person("張三",20);
}
@Conditional({WindowsCondition.class})
@Bean("male")
public Person personMale(){
return new Person("lisi",33);
}
@Conditional({LinuxCondition.class})
@Bean("female")
public Person personFemale(){
return new Person("wanger",23);
}
@Bean
public ColorFactory colorFactoryBean(){
return new ColorFactory();
}
}
測試類文章來源:http://www.zghlxwxcb.cn/news/detail-623245.html
public class MainTest {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
@Test
public void testImport(){
printBeans(applicationContext);
//工廠bean獲取的是調(diào)用的是getObject創(chuàng)建的對象(Color類)
Object bean1 = applicationContext.getBean("colorFactoryBean");
Object bean2 = applicationContext.getBean("colorFactoryBean");
System.out.println(bean1);
System.out.println(bean2.getClass());//class com.atguigu.bean.Color
System.out.println(bean1==bean2);
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String name:beanDefinitionNames) {
System.out.println(name);
}
}
測試結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-623245.html
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookDAO
bookService
com.atguigu.bean.Color
com.atguigu.bean.Red
com.atguigu.bean.Blue
com.atguigu.bean.Yellow
person
female
colorFactoryBean
rainbow
color factory generate a instance
color factory generate a instance
com.atguigu.bean.Color@79c97cb
class com.atguigu.bean.Color
false
到了這里,關(guān)于spring注解驅(qū)動(dòng)開發(fā)(一)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!