构建maven工程,在springMvc 、servlet 3.0 基础上
引入spring Security 依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>5.0.1.RELEASE</version>
</dependency>
配置Spring容器 ,创建ApplicationConfig类相当于applicationContext.xml配置文件
@Configuration
@ComponentScan(basePackages="",excludeFilters={})
public class ApplicationConfig{
// 配置除了Controller的其他bean
}
Servlet Context配置创建WebCongfig类
@Configuration
@EnbleWebMvc
@ComponentScan(basePackages="",includefilters ={})
public class WebConfig implements WebMvcConfigurer{
//视频解析器 等
}
Security 提供了认证授权拦截的功能,不需要再单独定义拦截器。
加载spring容器
public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
//servlet容器,相当于加载applicationContext.xml
@Override
protected Class<?>[] getRootConfigClasses (){
return new Class[]{
ApplicationConfig.class,
WebSecurityConfig.class
};
}
//servletContext,相当于加载springMvc.xml
@Override
protected Class<?>[] getServletConfigClasses(){
return new Class[]{
WebConfig.class
};
}
//url-mapping
@Override
protected Class<?>[] getServletMappings() {
return new String[]{"/"};
}
}
Spring Security初始化
- 若当前环境没有使用Spring或者SpringMvc,则需要把SpringSecurity配置类传入超类,以确保获取配置并创建spring context
- 相反则在现有的SpringContext中注册SpringSecurity配置类
public class SpringSecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
public SpringSecurityApplicationInitializer(){
// supper(WebSecurityConfig.class); 使用Spring 和SpringMvc 不用写
}
}
改造集成Springboot
添加Springboot依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
//dependencies下 添加
<!-->spring-boot 整合security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
区别:
- 加载spring容器的类ApplicationConfig不用写,Springboot自动完成
- 由于Springboot的自动装配技术WebConfig类的@EnableWebMvc 和 @ComponentScan() 注解不用写
- spring容器的加载类不用写
- SpringSenurity的环境初始化类不用写