1. 通过 @Import注解我们可以加载没有@Service @Component 注解的类到spring容器中
我们先看下 @Import的源码
我们可以通过实现这个接口自定义要加载的类
2.
package com.activity.study; import java.net.URLClassLoader; import java.util.List; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.type.AnnotationMetadata; public class UserSelector implements ImportSelector{ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { // List<String> strs = SpringFactoriesLoader.loadFactoryNames(EnableUser.class, URLClassLoader.getSystemClassLoader()); // return strs.toArray(new String[] {}); return new String[] {"com.activity.study.UserMeetting"}; } }
返回要加载的类的路径即可.
然后我们就可以通过@Autowired注入Bean
3.
package com.activity.study; import java.net.URLClassLoader; import java.util.List; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.type.AnnotationMetadata; public class UserSelector implements ImportSelector{ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { List<String> strs = SpringFactoriesLoader.loadFactoryNames(EnableUser.class, URLClassLoader.getSystemClassLoader()); return strs.toArray(new String[] {}); //return new String[] {"com.activity.study.UserMeetting"}; } }
或者在
resources 文件夹下面创建 META-INF/spring.factories 文件,
里面可以配置要注入的Bean
com.activity.study.EnableUser =
com.activity.study.UserMeetting
4.之后可以自定义注解加入@Import即可
package com.activity.study; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({UserSelector.class}) public @interface EnableUser { }
也可以直接在spring的启动类上加@Import,不过多个中间注解更简洁,也便于修改
@Enable的底层实现就是这样,最底层还是通过反射加载Class<?>类信息.