您好,登錄后才能下訂單哦!
如何使用@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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。