Bean加载控制
控制Bean加载:
在入门案例中,如果有不想被加载的bean,在Spring加载的bean加载Spring的时候有两种方式可以使用
方式:
Spring加载的bean设定扫描范围为com.forelink,排除掉controller包内的bean
//在ComponentScan注解后加入参数,限定扫描范围
@ComponentScan({"com.forelink.service","com.forelink.dao"})
public class SpringConfig{
}
扫描Dao包,通用性会好 如果不用Mybatis技术,用其他技术,也要扫描Dao包。 能把数据层包括进来,属于标准开发的一种 后续更改数据层就不用修改。
也可以使用排除的方法。
//使用排除方法
@ComponentScan(value="com.forelink",
excludeFilters = @ComponentScan.Filter(
//需要一个参数type,FilterType.[过滤策略]
//此处是过滤注解
type = FilterType.ANOTATION,
//过滤 com.forelink 中的 Controller 注解
classes = Controller.class
)
)
public class SpringConfig{
}
也有includeFilter,可以加载指定的bean。 可以写一个测试类进行效果测试
public class App {
public static void main(String[] args) {
// AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
// ctx.register(SpringConfig.class);
//也可以用这种方式来注册Spring配置文件
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println(ctx.getBean(UserController.class));;
}
}
会弹出报错,提示加载不了带有Controller的Bean,成功。
要注意带@configuration注解的,都有加载bean的功能。
Springboot中 通过Filter来对Bean的精细粒子度进行的控制
还有一种方式是,不对Spring会SpringMVC加以区分,都加载到环境中。 创建多个容器。
bean配置文件的加载:
ServletContainersInitConfig可以继承AbstractAnnotationConfigDispatcherServletInitializer,来简化开发流程
public class ServletContainerInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
//RootConfig配Spring的内容
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
//ServletConfig下配置SpringMVC的内容
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
//与下列内容是一样的
//public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer{
// @Override
// protected WebApplicationContext createServletApplicationContext() {
// AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// ctx.register(SpringMvcConfig.class);
// return ctx;
// }
// @Override
// protected String[] getServletMappings() {
// return new String[]{"/"};
// }
// @Override
// protected WebApplicationContext createRootApplicationContext() {
// AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// ctx.register(SpringConfig.class);
// }
//}