• 周六. 12 月 21st, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Spring注解驱动开发之IOC

admin

11 月 28, 2021

1、最简单的注解驱动开发实例:

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.3.8.RELEASE</version>
      </dependency>
public class Student {
    String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void print(){
        System.out.println("student :" + name);
    }
    public Student() {
        System.out.println("student构造器");
    }
}

@Configuration
public class Config {
    @Bean
    public Student student(){
        System.out.println("创建student对象");
        Student s = new Student();
        s.setName("yaohuiqin");
        return s;
    }
}

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext=new AnnotationConfigApplicationContext(Config.class);
        Student s= (Student) annotationConfigApplicationContext.getBean(Student.class);
        System.out.println(s.getName());
        String[] strings=annotationConfigApplicationContext.getBeanDefinitionNames();
        for(String ss:strings){
            System.out.println(ss);
        }
    }
}

2、@ComponentScan注解 自动扫描  @Controller  @Service @Repository @Component

FilterType.ANNOTATION:按照注解
FilterType.ASSIGNABLE_TYPE:按照给定的类型
FilterType.CUSTOM :自定义类型
<context:component-scan base-package="com.test.spring"></context:component-scan>
@Configuration
@ComponentScan(value = "com.test.spring.config",includeFilters={
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = Service.class)
},useDefaultFilters =false)
public class Config {

}
public class MyTypeFilger implements TypeFilter {
    /**
     *
     * @param metadataReader 扫描到的当前的类的信息
     * @param metadataReaderFactory 可以获取其他类的信息
     * @return
     * @throws IOException
     */
    @Override
    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;
        return false;
    }
}
@Configuration
@ComponentScan(value = "com.test.spring.config",includeFilters={
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = MyTypeFilger.class)
},useDefaultFilters =false)
public class config {
  
}

3、@Scope(value = “singleton”)

singleton、prototype、request、session
@Lazy懒加载

4@import(快速给容器导入一个组件)

@Import(value = {MyImportBeanDefinitionRegistrar.class,Dao.class})
value值可以是bean的类,
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinition beanDefinition = new RootBeanDefinition(ByBeanDefinitionRegistrar.class);
        registry.registerBeanDefinition("ByBeanDefinitionRegistrar123",beanDefinition);
    }
}

public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.test.spring.config.Dao","com.test.spring.config.Service"};
    }
}

5、@conditional使用实例

@Configuration
public class config2 {

    @Conditional(value = Linuxcondition.class)
    @Bean
    public Person yaohuiqin(){
        System.out.println("创建Person:yaohuiqin对象");
        Person s = new Person();
        s.setName("yaohuiqin");
        return s;
    }
}

public class Linuxcondition implements Condition  {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        ClassLoader classLoader = context.getClassLoader();
        Environment environment = context.getEnvironment();
        String currentOs = environment.getProperty("os.name");
        System.out.println(currentOs);
        if(currentOs.contains("Windows"))return true;
        return false;
    }
}

6、实现FactoryBean接口

public class NextDate implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        date = calendar.getTime();
        return date;
    }
    @Override
    public Class<?> getObjectType() {
        return Date.class;
    }
    @Override
    public boolean isSingleton() {
        return false;
    }
}

7、指定初始化方法和销毁方法

@Bean(initMethod = “init”,destroyMethod = “destory”)    初始化和销毁方法指定。初始化方法是在对象创建完成并赋完值,则调初始化方法。销毁方法是在容器销毁时调用。

@PostConstruct

@PreDestroy 

public class MyCat implements InitializingBean,DisposableBean {
    String name;
    public MyCat() {
        System.out.println("MyCat构造器");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        System.out.println("设置属性");
        this.name = name;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("MyCat---InitializingBean----afterPropertiesSet()");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean---DisposableBean---destroy()");
    }
}

8、BeanPostProcessor接口

Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

源码:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
populateBean(beanName, mbd, instanceWrapper);   //给bean进行属性赋值
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}


9、@Value赋值
  值,#{},${}        #{20-2}

 <context:property-placeholder location="jdbc.properties"></context:property-placeholder>
等价于在配置类上写:@PropertySource( value = "jdbc.properties")

10、自动装配

  @Autowired 优先使用类型去自动装配,如果存在多个,则将属性的名字作为id去查找装配。

  指定装配:

    @Qualifier("myDao2")
    @Autowired
    MyDao myDao3;
 装配时首选装配:
    @Primary
  找不到就不装配 :
    @Autowired(required = false)

发表回复