@Import配置bean的几种方式

2019-01-16  本文已影响0人  胖嘟嘟洒酒疯

car定义

package com.example.demo.bean;

public class Car {

    public void speakOnself(){
        System.out.println("Car");
    }
}

cat定义

package com.example.demo.bean;

public class Cat {

    public void speakOneself(){
        System.out.println("cat");
    }
}

person定义

package com.example.demo.model;

import lombok.Data;

@Data
public class Person {

    private String name;

    private Integer age;

    public void speakOneself(){
        System.out.println("person");
    }

}

配置类导入

package com.example.demo.config;

import com.example.demo.bean.Car;
import com.example.demo.importer.MyImportBeanDefinition;
import com.example.demo.importer.MyImportSelector;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Import({Car.class, MyImportSelector.class, MyImportBeanDefinition.class})
@Configuration
public class ImportAnnoExampleConfig {
}

MyImportSelector实现

package com.example.demo.importer;

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

public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        // 返回值为要实例化bean的全类名,数组
        return new String[]{"com.example.demo.model.Person"};
    }
}

MyImportBeanDefinition实现

package com.example.demo.importer;

import com.example.demo.bean.Cat;
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 MyImportBeanDefinition implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {

        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Cat.class);
        beanDefinitionRegistry.registerBeanDefinition("cat", rootBeanDefinition);
    }
}

验证:


@RestController
public class DemoController {

    @Autowired
    private Car car;

    @Autowired
    private Cat cat;

    @Autowired
    private Person person;

    @PostConstruct
    public void run(){
        car.speakOnself();
        person.speakOneself();
        cat.speakOneself();
    }

结果:

2019-01-16 19:46:09.383  INFO 1530 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1744 ms
Car
person
cat
上一篇下一篇

猜你喜欢

热点阅读