構(gòu)建maven工程怨规,在springMvc 灾部、servlet 3.0 基礎(chǔ)上
引入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容器 昏翰,創(chuàng)建ApplicationConfig類相當(dāng)于applicationContext.xml配置文件
@Configuration
@ComponentScan(basePackages="",excludeFilters={})
public class ApplicationConfig{
// 配置除了Controller的其他bean
}
Servlet Context配置創(chuàng)建WebCongfig類
@Configuration
@EnbleWebMvc
@ComponentScan(basePackages="",includefilters ={})
public class WebConfig implements WebMvcConfigurer{
//視頻解析器 等
}
Security 提供了認(rèn)證授權(quán)攔截的功能或渤,不需要再單獨(dú)定義攔截器罢维。
加載spring容器
public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
//servlet容器,相當(dāng)于加載applicationContext.xml
@Override
protected Class<?>[] getRootConfigClasses (){
return new Class[]{
ApplicationConfig.class,
WebSecurityConfig.class
};
}
//servletContext,相當(dāng)于加載springMvc.xml
@Override
protected Class<?>[] getServletConfigClasses(){
return new Class[]{
WebConfig.class
};
}
//url-mapping
@Override
protected Class<?>[] getServletMappings() {
return new String[]{"/"};
}
}
Spring Security初始化
- 若當(dāng)前環(huán)境沒有使用Spring或者SpringMvc玉吁,則需要把SpringSecurity配置類傳入超類照弥,以確保獲取配置并創(chuàng)建spring context
- 相反則在現(xiàn)有的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>
區(qū)別:
- 加載spring容器的類ApplicationConfig不用寫,Springboot自動完成
- 由于Springboot的自動裝配技術(shù)WebConfig類的@EnableWebMvc 和 @ComponentScan() 注解不用寫
- spring容器的加載類不用寫
- SpringSenurity的環(huán)境初始化類不用寫