spring注解开发
程序员文章站
2022-03-05 12:03:05
...
spring注解开发常用注解
[email protected] //告诉spring这是一个配置类
配置类1
//配置类就是配置文件
@Import(value = {Color.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
@Configuration //告诉spring这是一个配置类
@ComponentScan(value = {"com.atguigu"},excludeFilters = {
/* @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, Service.class}),*/
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyTypeFilter.class})})
public class MainConfig {
//@ComponentScan value:指定要扫描的包
//excludeFilters = Filter[] :指定扫描的时候按照什么规则排除那些组件
//includeFilters = Filter[] :指定扫描的时候只需要包含哪些组件
//FilterType.ANNOTATION:按照注解
//FilterType.ASSIGNABLE_TYPE:按照给定的类型;
//FilterType.ASPECTJ:使用ASPECTJ表达式
//FilterType.REGEX:使用正则指定
//FilterType.CUSTOM:使用自定义规则
@Bean(value = {"person22"})//给容器中注册一个bean,类型为返回值的类型,id默认为方法名
public Person person(){
return new Person("lisi",20);
}
}
配置类2
package com.atguigu.config;
import com.atguigu.bean.Person;
import com.atguigu.linuxcondition.LinuxCondition;
import com.atguigu.windowscondition.WindowsCondition;
import org.springframework.context.annotation.*;
@Configuration
public class MainConfig2 {
@Lazy
@Bean
@Scope("prototype")//scope控制Bean作用范围
public Person person(){
/**
* Specifies the name of the scope to use for the annotated component/bean.
* <p>Defaults to an empty string ({@code ""}) which implies
* {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
* @since 4.2
* @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
* @see ConfigurableBeanFactory#SCOPE_SINGLETON
* @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
* @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
* @see #value
*
* * @Scope:调整作用域
* prototype:多实例的:ioc容器启动并不会去调用方法创建对象放在容器中。
* 每次获取的时候才会调用方法创建对象;
* singleton:单实例的(默认值):ioc容器启动会调用方法创建对象放到ioc容器中。
* 以后每次获取就是直接从容器(map.get())中拿,
* request:同一次请求创建一个实例
* session:同一个session创建一个实例
*
* 懒加载:
* 单实例bean:默认在容器启动的时候创建对象;
* 懒加载:容器启动不创建对象。第一次使用(获取)Bean创建对象,并初始化;
*/
return new Person("张三",15);
}
/**
* @Conditional({Condition}) : 按照一定的条件进行判断,满足条件给容器中注册bean
*
* 如果系统是windows,给容器中注册("bill")
* 如果是linux系统,给容器中注册("linus")
*/
@Conditional({WindowsCondition.class})
@Bean("bill")
public Person person01(){
return new Person("比尔盖茨",99);
}
@Conditional({LinuxCondition.class})
@Bean("linus")
public Person person02(){
return new Person("linus",55);
}
/**
* 给容器中注册组件;
* 1)、包扫描+组件标注注解(@Controller/@Service/@Repository/@Component)[自己写的类]
* 2)、@Bean[导入的第三方包里面的组件]
* 3)、@Import[快速给容器中导入一个组件]
* 1)、@Import(要导入到容器中的组件);容器中就会自动注册这个组件,id默认是全类名
* 2)、ImportSelector:返回需要导入的组件的全类名数组;
* 3)、ImportBeanDefinitionRegistrar:手动注册bean到容器中
* 4)、使用Spring提供的 FactoryBean(工厂Bean);
* 1)、默认获取到的是工厂bean调用getObject创建的对象
* 2)、要获取工厂Bean本身,我们需要给id前面加一个&
* &colorFactoryBean
*/
}
自定义规则针对 @ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyTypeFilter.class})})
package com.atguigu.config;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;
import java.io.IOException;
public class MyTypeFilter implements TypeFilter{
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//获取当前类注解的信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//获取当前正在扫描的类的类信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//获取当前类资源(类的路径)
Resource resource = metadataReader.getResource();
//获取类名
String className = classMetadata.getClassName();
System.out.println("---"+className);
if(className.contains("er")){
return true;
}else{
return false;
}
}
}
@Conditional
定义过滤规则
package com.atguigu.windowscondition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class WindowsCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String osName = environment.getProperty("os.name");
if(osName.contains("Windows")){
return true;
}else{
return false;
}
}
}
package com.atguigu.linuxcondition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
/*ConditionContext能使用的上下文环境
*AnnotatedTypeMetadata 注释信息
* */
public class LinuxCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//判断是否是Linux系统
//1.能获取ioc使用的BeanFactory
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//2.获取类加载器
ClassLoader classLoader = context.getClassLoader();
//3.获取当前环境信息
Environment environment = context.getEnvironment();
//4.获取到Bean定义的注册类
BeanDefinitionRegistry registry = context.getRegistry();
String osName = environment.getProperty("os.name");
if(osName.contains("linux")){
return true;
}else {
return false;
}
}
}
@Import(value = {Color.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
利用上述ImportSelector和ImportBeanDefinitionRegistrar给容器注册组件
MyImportSelector类代码
package com.atguigu.condition;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import java.util.Set;
//自定义逻辑返回需要导入的组件
public class MyImportSelector implements ImportSelector {
//返回值,就是到导入到容器中的组件全类名
//AnnotationMetadata:当前标注@Import注解的类的所有注解信息
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.atguigu.bean.Blue","com.atguigu.bean.Yellow"};
}
}
MyImportBeanDefinitionRegistrar类代码
package com.atguigu.condition;
import com.atguigu.bean.RainNow;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
/**
* AnnotationMetadata:当前类的注解信息
* BeanDefinitionRegistry:BeanDefinition注册类;
* 把所有需要添加到容器中的bean;调用
* BeanDefinitionRegistry.registerBeanDefinition手工注册进来
*/
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean red = registry.containsBeanDefinition("com.atguigu.bean.Blue");
boolean yellow = registry.containsBeanDefinition("com.atguigu.bean.Yellow");
BeanDefinition beanDefinition = new RootBeanDefinition(RainNow.class);
if(red&&yellow){
registry.registerBeanDefinition("rainNow",beanDefinition);
}
}
}
测试代码
package com.atguitu.test;
import com.atguigu.config.MainConfig;
import com.atguigu.config.MainConfig2;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class IOCtest {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
@Test
public void testImport(){
printBeans(applicationContext);
}
public void printBeans(AnnotationConfigApplicationContext annotationConfigApplicationContext){
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
for (String s:beanDefinitionNames
) {
System.out.println(s);
}
}
@SuppressWarnings("resource")
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String s:beanDefinitionNames
) {
System.out.println(s);
}
}
@SuppressWarnings("resource")
@Test
public void test02(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String s:beanDefinitionNames
) {
System.out.println(s);
}
Object bean = applicationContext.getBean("person");
Object bean2 = applicationContext.getBean("person");
System.out.println(bean==bean2);
}
@SuppressWarnings("resource")
@Test
public void test03(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
ConfigurableEnvironment environment = applicationContext.getEnvironment();
//获取环境变量的值windows 10
String osname = environment.getProperty("os.name");
System.out.println(osname);
for (String s:beanDefinitionNames
) {
System.out.println(s);
}
}
}