如何使用@import导入实现了ImportBeanDefinitionRegistrar接口的类
在程序开发的时候,我们经常会遇见一个名词“接口”这也是我们做开发人员工作中必不可少的一个技术,接下来就和大家分享一下怎么使用@import导入实现了ImportBeanDefinitionRegistrar接口的类。
package com.example.demo9;
import com.example.demo9.server.MyServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class Demo9Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Demo9Application.class, args);
String[] beanNamesForType = context.getBeanNamesForType(MyServer.class);
System.out.println(Arrays.asList(beanNamesForType).toString());
context.close();
}
}
public interface MyServer {
void fun();
}
package com.example.demo9.server;
//这里最好不要加@Service,除非有其它要求
public class MyServerAImp implements MyServer{
@Override
public void fun() {
System.out.println("MyServerAImp>>>>>>>>>>>>>>");
}
}
package com.example.demo9.server;
//这里最好不要加@Service,除非有其它要求
public class MyServerBImp implements MyServer{
@Override
public void fun() {
System.out.println("MyServerBImp>>>>>>>>>>>>>>");
}
}
package com.example.demo9.registrar;
import com.example.demo9.server.MyServerAImp;
import com.example.demo9.server.MyServerBImp;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//GenericBeanDefinition对象设置BeanDefinition
GenericBeanDefinition genericBeanDefinitionMyServerAImp=new GenericBeanDefinition();
genericBeanDefinitionMyServerAImp.setBeanClass(MyServerAImp.class);
GenericBeanDefinition genericBeanDefinitionMyServerBImp=new GenericBeanDefinition();
genericBeanDefinitionMyServerBImp.setBeanClass(MyServerBImp.class);
//注册
registry.registerBeanDefinition("genericBeanDefinitionMyServerAImp",genericBeanDefinitionMyServerAImp);
registry.registerBeanDefinition("genericBeanDefinitionMyServerBImp",genericBeanDefinitionMyServerBImp);
}
}
package com.example.demo9.configuration;
import com.example.demo9.registrar.MyImportBeanDefinitionRegistrar;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(MyImportBeanDefinitionRegistrar.class)
public class MyConfiguration {
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。