spring--注解---IOC

Posted 周无极

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring--注解---IOC相关的知识,希望对你有一定的参考价值。

    spring--注解---IOC(3)

 

 

package com.zwj.bean;

public class Blue {
    
    public Blue(){
        System.out.println("blue...constructor");
    }
    
    public void init(){
        System.out.println("blue...init...");
    }
    
    public void detory(){
        System.out.println("blue...detory...");
    }
}
Blue
package com.zwj.bean;

import org.springframework.stereotype.Component;

@Component
public class Car {
    
    public Car(){
        System.out.println("car constructor...");
    }
    
    public void init(){
        System.out.println("car ... init...");
    }
    
    public void detory(){
        System.out.println("car ... detory...");
    }

}
Car
package com.zwj.bean;

public class Color {
    
    private Car car;

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Color [car=" + car + "]";
    }
    
    

}
Color
package com.zwj.bean;

import org.springframework.beans.factory.FactoryBean;

//创建一个Spring定义的FactoryBean
public class ColorFactoryBean implements FactoryBean<Color> {

    //返回一个Color对象,这个对象会添加到容器中
    @Override
    public Color getObject() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("ColorFactoryBean...getObject...");
        return new Color();
    }

    @Override
    public Class<?> getObjectType() {
        // TODO Auto-generated method stub
        return Color.class;
    }

    //是单例?
    //true:这个bean是单实例,在容器中保存一份
    //false:多实例,每次获取都会创建一个新的bean;
    @Override
    public boolean isSingleton() {
        // TODO Auto-generated method stub
        return false;
    }

}
ColorFactoryBean
package com.zwj.bean;

public class RainBow {

}
RainBow
package com.zwj.bean;

public class Yellow {

}
Yellow
package com.zwj.condition;

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;

import com.zwj.bean.RainBow;


public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * AnnotationMetadata:当前类的注解信息
     * BeanDefinitionRegistry:BeanDefinition注册类;
     *         把所有需要添加到容器中的bean;调用
     *         BeanDefinitionRegistry.registerBeanDefinition手工注册进来
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        
        boolean definition = registry.containsBeanDefinition("com.zwj.bean.Yellow");
        boolean definition2 = registry.containsBeanDefinition("com.zwj.bean.Blue");
        if(definition && definition2){
            //指定Bean定义信息;(Bean的类型,Bean。。。)
            RootBeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
            //注册一个Bean,指定bean名
            registry.registerBeanDefinition("rainBow", beanDefinition);
        }
    }

}
MyImportBeanDefinitionRegistrar
package com.zwj.condition;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

//自定义逻辑返回需要导入的组件
public class MyImportSelector implements ImportSelector {

    //返回值,就是到导入到容器中的组件全类名
    //AnnotationMetadata:当前标注@Import注解的类的所有注解信息
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // TODO Auto-generated method stub
        //importingClassMetadata
        //方法不要返回null值
        return new String[]{"com.zwj.bean.Blue","com.zwj.bean.Yellow"};
    }

}
MyImportSelector
package com.zwj.config;



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;

import com.zwj.bean.Car;
import com.zwj.bean.Color;
import com.zwj.bean.ColorFactoryBean;
import com.zwj.condition.MyImportBeanDefinitionRegistrar;
import com.zwj.condition.MyImportSelector;


@Configuration
@Import({Car.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})
//@Import导入组件,id默认是组件的全类名
public class MainConfig2 {
    

    /**
     * 给容器中注册组件;
     * 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
     */
    @Bean
    public ColorFactoryBean colorFactoryBean(){
        return new ColorFactoryBean();
    }
    
    
    

}
MainConfig2
package com.zwj.test;

import static org.junit.Assert.*;


import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.zwj.bean.Blue;
import com.zwj.config.MainConfig2;


public class IOCTest {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
    @Test
    public void testImport(){
        printBeans(applicationContext);
        Blue bean = (Blue) applicationContext.getBean(Blue.class);
        System.out.println(bean);
        
        //工厂Bean获取的是调用getObject创建的对象
        Object bean2 = applicationContext.getBean("colorFactoryBean");
        Object bean3 = applicationContext.getBean("colorFactoryBean");
        System.out.println("bean的类型:"+bean2.getClass());
        System.out.println(bean2 == bean3);
        
        Object bean4 = applicationContext.getBean("&colorFactoryBean");
        System.out.println(bean4.getClass());
    }
    
    private void printBeans(AnnotationConfigApplicationContext applicationContext){
        String[] definitionNames = applicationContext.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println(name);
        }
    }

}

/*
 mainConfig2
com.zwj.bean.Car
com.zwj.bean.Blue
com.zwj.bean.Yellow
colorFactoryBean
rainBow
com.zwj.bean.Blue@341b80b2
ColorFactoryBean...getObject...
ColorFactoryBean...getObject...
bean的类型:class com.zwj.bean.Color
false
class com.zwj.bean.ColorFactoryBean
 */
IOCTest
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zwj</groupId>
  <artifactId>spring-annotation_IOC</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
pom.xml

 

以上是关于spring--注解---IOC的主要内容,如果未能解决你的问题,请参考以下文章

Spring之IOC与DI注解

Spring第二天——IOC注解操作与AOP概念

IOC——Spring的bean的管理(注解方式)

Spring-IOC容器-Bean管理-基于注解方式详解

Java开发Spring之IOC详解第二篇(注解开发JdbcTemplatem模板Junit整合)

Spring5学习笔记 — “IOC操作Bean管理(基于注解)”