Let's modify last example to see how to use a user defined annotation along with ImportSelector.
Creating a custom annotation
package com.logicbig.example;
import org.springframework.context.annotation.Import;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(MyImportSelector.class)
public @interface EnableSomeModule {
String value() default "";
}
Implementing ImportSelector
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
AnnotationAttributes attributes = AnnotationAttributes.fromMap(
importingClassMetadata.getAnnotationAttributes(
EnableSomeModule.class.getName(), false));
String value = attributes.getString("value");
if ("someValue".equals(value)) {
return new String[]{MyConfig1.class.getName()};
} else {
return new String[]{MyConfig2.class.getName()};
}
}
}
MainConfig
In our main configuration class we will use our new annotation instead of directly using @Import:
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableSomeModule("someValue")
public class MainConfig {
@Bean
ClientBean clientBean() {
return new ClientBean();
}
}
Config 1
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig1 {
@Bean
AppBean appBean() {
return new AppBean("from config 1");
}
}
Config 2
@Configuration
public class MyConfig2 {
@Bean
AppBean appBean() {
return new AppBean("from config 2");
}
}
Beans
package com.logicbig.example;
public class AppBean {
private String message;
public AppBean(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
public class ClientBean {
@Autowired
private AppBean appBean;
public void doSomething() {
System.out.println(appBean.getMessage());
}
}
Main class
package com.logicbig.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ImportSelectorWithAnnotationExample {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(
MainConfig.class);
ClientBean bean = context.getBean(ClientBean.class);
bean.doSomething();
}
}
Outputfrom config 1
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 3.2.9.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 25
- Maven 3.9.11
|