JAVA--Spring核心配置拓展
Spring Boot核心配置与扩展
一、配置加载
1. 配置文件类型
多种格式的配置文件:
- application.properties:传统的键值对格式
- application.yml:更简洁的YAML格式
- application.yaml:与yml格式相同,只是文件扩展名不同
2. 配置属性读取
-
@Value注解:直接使用
@Value("${user.name555}") private String name; -
@ConfigurationProperties注解:批量绑定配置属性到对象
二、IOC管理
1. 什么是IOC
IOC是Spring的核心概念,它将对象的创建和管理交给Spring容器,而不是由开发者手动创建。
2. Bean的定义与注册
在项目中,通过以下方式定义和注册Bean:
- @Bean注解:在配置类中使用
@Bean public User user1(){ return new User(name, password); }
3. 配置类
使用@Configuration注解标记的类称为配置类,用于集中管理Bean的定义:
@Configuration
public class BeanConfiguration {
}
三、拦截器应用
1. 拦截器介绍
拦截器是Spring MVC的重要组件,它可以在请求处理前后执行特定的逻辑,类似于过滤器,但拦截器更专注于业务逻辑处理。
2. 拦截器的实现
-
创建拦截器类:实现HandlerInterceptor接口
public class Timeintercept implements HandlerInterceptor { } -
注册拦截器
@Configuration public class WebConfiguration implements WebMvcConfigurer { @Bean public Timeintercept timeintercept() { return new Timeintercept(); } }
3. 拦截器的执行流程
- preHandle:请求处理前执行,返回true继续处理,返回false中断处理
- postHandle:控制器方法执行后执行
四、项目实战应用
1. 配置加载示例
在BeanConfiguration.java中,通过@Bean注解定义Bean:
@Configuration
public class BeanConfiguration {
@Value("${user.name555}")
private String name;
@Value("${user.password555}")
private String password;
@Bean
public User user1(){
return new User(name, password);
}
@Bean
public User user2(){
return new User(name+"2", password);
}
}
2. IOC管理
在WebConfiguration.java中,通过@Autowired注入Timeintercept,然后通过@Bean注册:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Autowired
private Timeintercept timeintercept;
@Bean
public Timeintercept timeintercept(){
return new Timeintercept();
}
}
3. 拦截器
在Timeintercept.java中,实现了一个简单的时间拦截器,用于记录请求处理时间:
public class Timeintercept implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了,记录开始时间");
long t2 = new Date().getTime();
request.setAttribute("startTime", t2);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long t1 = (long) request.getAttribute("startTime");
long t2 = new Date().getTime();
System.out.println(request.getRequestURI()+"耗时:"+(t2-t1));
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
}

浙公网安备 33010602011771号