1。javaConfig,使用java类代替xml配置文件使用,是配置spring容器的纯java方式
使用的两个注解
@Configuration 放在类上
@Bean 放在方法上 ,这个注解里面不配置name,那么这个方法名就是bean的id
@ImportResource,导入其他的xml配置文件,等价于
<import resource="其他配置文件">
@Configuration
@ImportResource(value = "classpath:application.xml")
public class SpringConfig {
@Bean
public Student getStudent(){
Student student = new Student();
student.setAge(20);
student.setName("李四");
student.setSex("男");
return student;
}
}
@PropertySource,读取外部配置文件,使用配置文件可以实现外部化配置,在程序代码之外提供数据, 在resources目录下创建properties文件 k=v的格式
在PropertySource指定property文件的位置,使用@Value("${key}")注解给属性赋值
设置property文件需要注意把idea的编码格式设置为utf-8 ,设置方法 FILE--->SETTING--->查找encoding,全部设置为utf-8
配置类 ,因为Configuration替换了xml,而下面的三个注解都是在xml的替换方式,
@Configuration @ImportResource(value = "classpath:application.xml") @PropertySource(value = "classpath:config.properties") @ComponentScan(basePackages = "com.abc.vo") public class SpringConfig {
老虎类
@Component("tiger") public class Tiger { @Value("${tiger.name}") private String name; @Value("${tiger.age}") private Integer age;
测试类
ApplicationContext ct = new AnnotationConfigApplicationContext(SpringConfig.class);
Tiger tiger = (Tiger) ct.getBean("tiger");
System.out.println(tiger);
@SpringBootApplication 是一个符合注解
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
@SpringBootConfiguration,使用了这个注解标注的类是一个Configuration类,可以使用@Bean声明对象,注入容器中
@Configuration @Indexed public @interface SpringBootConfiguration { @AliasFor( annotation = Configuration.class ) boolean proxyBeanMethods() default true; }
@EnableAutoConfiguration,启用自动配置,把java对象配置好,放入到容器中,例如,把mybatis的对象创建好,放到容器中
@ComponentScan,扫描器,找到注解,根据注解的功能创建对象,给属性赋值,默认扫描的包,@ComponentScan所在的类所在的包和子包
springboot的配置文件
文件名 application properties格式
server.port=8082 server.servlet.context-path=/myboot
yml格式
server: port: 8083 servlet: context-path: /myboot2
多环境配置
创建多个配置文件,文件名称为 application-环境名称.properties或者.yml
如开发环境 application-dev.yml 测试环境 application-test.yml
spring.profiles.active=dev,这个就是配置使用application-dev.yml
@Value的使用
@Value("${key}"), key来自于application.yml文件
school: name: 大学校 add: 123
@Value("${school.name}") private String name; @Value("${school.add}") private String add;
@ConfigurationProperties 给对象的属性赋值,在使用这个时会有提示,需要加上下面的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
@Component //这里把对象加入到容器后,在其他地方就可以把这个对象注入使用了 @ConfigurationProperties(prefix = "school") public class School { private String name; private String add; 加上get和set方法
使用容器
使用代码从容器中获取对象,可以使用run方法的返回值
public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(DuohuanjingApplication.class, args); UserService u = (UserService) ctx.getBean("userService"); u.f1();
ConfigurableApplicationContext 是ApplicationContext的子接口,这里一般在开发过程中自己测试时使用
CommandLineRunner接口和ApplicationRunner接口
这两个接口都有一个run方法, 执行时间在容器对象创建好后,自动执行run()方法,可以完成自定义的在容器对象创建好后的一些操作
@SpringBootApplication public class DuohuanjingApplication implements CommandLineRunner { @Resource private UserService userService; public static void main(String[] args) { System.out.println("容器对象创建之前"); 第一输出 ConfigurableApplicationContext ctx = SpringApplication.run(DuohuanjingApplication.class, args); System.out.println("容器对象创建之后"); 第三输出 UserService u = (UserService) ctx.getBean("userService"); u.f1(); } @Override public void run(String... args) throws Exception { System.out.println("这里是main方法的run执行之后接着执行的"); 第二输出 这里可以在上面的主类里注入bean,然后这里直接调用bean的方法 userService.say(); } }
拦截器
拦截器是springmvc的一种对象,能拦截对controller的请求,拦截器框架中有系统的拦截器,我们还可以自定义拦截器,完成对请求的预处理
自定义拦截器
1. 定义一个类实现springmvc框架中的HandlerInterceptor接口
public interface HandlerInterceptor { default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; //返回false则拦截 } default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { } default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
2.
SpringBoot中使用拦截器的步骤
1.定义一个类实现springmvc框架中的HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("执行拦截器。。。"); return true; } }
2.定义一个配置类实现 WebMvcConfigurer接口,重写 addInterceptors方法
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { HandlerInterceptor interceptor = new MyInterceptor(); String[] paths={"/usr/add"}; //要拦截的请求,controller中配置的 String[] exclupath={"/usr/login"}; //放行的请求不拦截,controller中配置的 registry.addInterceptor(interceptor).addPathPatterns(paths).excludePathPatterns(exclupath); } }
springboot中使用Servlet步骤
1 定义一个类继承HttpServlet
public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.println("执行了Servlet"); out.flush(); out.close(); }
2.定义一个配置类注册servlet,通过ServletRegistrationBean注册bean
@Configuration public class ServletConfig { @Bean public ServletRegistrationBean getServletRegistrationBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(); bean.setServlet(new MyServlet()); Collection<String> c = new ArrayList<>(); c.add("/myservlet"); //访问这个地址会访问到servlet bean.setUrlMappings(c); return bean; } }
或者使用下面这句
@Bean public ServletRegistrationBean getServletRegistrationBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(); bean.setServlet(new MyServlet()); Collection<String> c = new ArrayList<>(); c.add("/myservlet"); c.add("/yourservlet"); bean.setUrlMappings(c); return bean;
springboot中使用Filter过滤器步骤
1.定义一个类实现Filter接口
public class MyFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("过滤器执行了"); filterChain.doFilter(servletRequest,servletResponse); } }
2.注册Filter对象
@Configuration public class FilterConfig { @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean fbean = new FilterRegistrationBean(); fbean.setFilter(new MyFilter()); fbean.addUrlPatterns("/usr/*"); return fbean; } }