@Import構成beanのいくつかの方法

2862 ワード

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