亲宝软件园·资讯

展开

Spring bean加载控制实现方法

给我手牵你走~~ 人气:0

1. Controller加载控制

因为功能不同,要避免Spring错误的加载到SpringMVC的bean

1.1 Controller加载控制与业务bean加载控制

SpringMVC相关bean(表现层bean)

Spring控制的bean

SpringMVC相关bean加载控制

Spring相关bean加载控制

1.2 加载Spring控制的bean的时候排除掉SpringMVC控制的bean(方式一)

名称:@ComponentScan

类型:类注解

范例

package com.zhang.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
@Configuration
@ComponentScan(value = "com.zhang", excludeFilters = @ComponentScan.Filter(
        type = FilterType.ANNOTATION,
        classes = Controller.class
))
public class SpringConfig {
}

属性

1.3 验证是否排除成功

创建spring容器加载spring配置文件,然后根据类型获取表现层的bean,如果不能获取则证明加载Spring控制的bean的时候成功排除掉SpringMVC控制的bean;这里值得一提的是,需要把SpringMVCConfig配置类上的@Configuration注释掉;

package com.zhang;
import com.zhang.config.SpringConfig;
import com.zhang.controller.UserController;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserController userController = context.getBean(UserController.class);
        System.out.println(userController);
    }
}

1.4 运行结果

证明加载Spring控制的bean的时候成功排除掉SpringMVC控制的bean

2. Bean的加载格式

extends AbstractDispatcherServletInitializer

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer { 
    protected WebApplicationContext createServletApplicationContext() { 
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;  
    }   
    protected WebApplicationContext createRootApplicationContext() {  
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();      
        ctx.register(SpringConfig.class);        
        return ctx;  
    }   
    protected String[] getServletMappings() { 
        return new String[]{"/"}; 
    }
}

简化格式

extends AbstractAnnotationConfigDispatcherServletInitializer

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class}
    };
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论