springboot中将对象加入容器的2种方式
1. 类注解+springboot入口类注解
例如: servlet:servlet类上加@WebServlet("/myServlet")+springboot +入口类上加@ServletComponentScan(basePackages = "******") filter:filter类上加@WebFilter(urlPatterns = "/some") +入口类上加@ServletComponentScan(basePackages = "******")
2. 配置类
注意,在springboot中声明配置类时加的@configuration注解,会自动将该类的对象放入容器
例如: servlet:去掉注解方式的2个注解,而声明一个加@Configuration的配置类和一个加@Bean的方法
package com.bjpowernode.springboot.config;
import...
@Configuration
public class ServletConfig {
@Bean
public ServletRegistrationBean myServletRegistrationBean() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
return servletRegistrationBean;
}
}
filter:去掉注解方法的2个注解,而声明一个加@Configuration的配置类和一个加@Bean的方法 (注意:过滤器中的路径为需要过滤的请求的路径,而非过滤器的路径)
package com.bjpowernode.springboot.config;
import ...
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
filterRegistrationBean.addUrlPatterns("/some");
return filterRegistrationBean;
}
}
interceptor:仍然不需要那2个注解,而声明一个加@Configuration的配置类,实现WebMvcConfigurer并重写addInterceptors方法
package com.bjpowernode.springboot.config;
import ...
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptor = registry.addInterceptor(new UserInterceptor());
String[] add = {
"/user/**"
};
String[] exclude = {
"/user/out", "/user/error", "/user/login"
};
interceptor = interceptor.addPathPatterns(add);
interceptor = interceptor.excludePathPatterns(exclude);
}
}
springboot与spring中向容器中加入对象的区别
springboot中的配置类就等价于 spring中xml写的<bean></bean> 标签+ Application context = new ClassPathXmlApplicationContext("******.xml"); Some some = context.getBean(Some.class);
也就是说springboot的配置类不仅完成了对象的创建,而且完成向容器中放对象的操作。
|