Spring 代码优化技巧(大全2)(二)

简介: Spring 代码优化技巧(大全2)

十四. @ConfigurationProperties赋值

我们在项目中使用配置参数是非常常见的场景,比如,我们在配置线程池的时候,需要在applicationContext.propeties文件中定义如下配置:

thread.pool.corePoolSize=5
thread.pool.maxPoolSize=10
thread.pool.queueCapacity=200
thread.pool.keepAliveSeconds=30

方法一:通过@Value注解读取这些配置。

public class ThreadPoolConfig {

@Value("${thread.pool.corePoolSize:5}")
private int corePoolSize;
@Value("${thread.pool.maxPoolSize:10}")
private int maxPoolSize;
@Value("${thread.pool.queueCapacity:200}")
private int queueCapacity;
@Value("${thread.pool.keepAliveSeconds:30}")
private int keepAliveSeconds;
@Value("${thread.pool.threadNamePrefix:ASYNC_}")
private String threadNamePrefix;
@Bean
public Executor threadPoolExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(corePoolSize);
    executor.setMaxPoolSize(maxPoolSize);
    executor.setQueueCapacity(queueCapacity);
    executor.setKeepAliveSeconds(keepAliveSeconds);
    executor.setThreadNamePrefix(threadNamePrefix);
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;
}

}

这种方式使用起来非常简单,但建议在使用时都加上:,因为:后面跟的是默认值,比如:@Value(“${thread.pool.corePoolSize:5}”),定义的默认核心线程数是5。

假如有这样的场景:business工程下定义了这个ThreadPoolConfig类,api工程引用了business工程,同时job工程也引用了business工程,而ThreadPoolConfig类只想在api工程中使用。这时,如果不配置默认值,job工程启动的时候可能会报错。

如果参数少还好,多的话,需要给每一个参数都加上@Value注解,是不是有点麻烦?

此外,还有一个问题,@Value注解定义的参数看起来有点分散,不容易辨别哪些参数是一组的。

这时,@ConfigurationProperties就派上用场了,它是springboot中新加的注解。

第一步,先定义ThreadPoolProperties类

@Data
@Component
@ConfigurationProperties("thread.pool")
public class ThreadPoolProperties {
    private int corePoolSize;
    private int maxPoolSize;
    private int queueCapacity;
    private int keepAliveSeconds;
    private String threadNamePrefix;
}

第二步,使用ThreadPoolProperties类

@Configuration
public class ThreadPoolConfig {
    @Autowired
    private ThreadPoolProperties threadPoolProperties;
    @Bean
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

使用@ConfigurationProperties注解,可以将thread.pool开头的参数直接赋值到ThreadPoolProperties类的同名参数中,这样省去了像@Value注解那样一个个手动去对应的过程。

这种方式显然要方便很多,我们只需编写xxxProperties类,spring会自动装配参数。此外,不同系列的参数可以定义不同的xxxProperties类,也便于管理,推荐优先使用这种方式。

它的底层是通过:ConfigurationPropertiesBindingPostProcessor类实现的,该类实现了BeanPostProcessor接口,在postProcessBeforeInitialization方法中解析@ConfigurationProperties注解,并且绑定数据到相应的对象上。

绑定是通过Binder类的bindObject方法完成的:

以上这段代码会递归绑定数据,主要考虑了三种情况:

  • bindAggregate 绑定集合类
  • bindBean 绑定对象
  • bindProperty 绑定参数 前面两种情况最终也会调用到bindProperty方法。

「此外,友情提醒一下:」

使用@ConfigurationProperties注解有些场景有问题,比如:在apollo中修改了某个参数,正常情况可以动态更新到@ConfigurationProperties注解定义的xxxProperties类的对象中,但是如果出现比较复杂的对象,比如:

private Map<String, Map<String,String>>  urls;

可能动态更新不了。

这时候该怎么办呢?

答案是使用ApolloConfigChangeListener监听器自己处理:

@ConditionalOnClass(com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig.class)
public class ApolloConfigurationAutoRefresh implements ApplicationContextAware {
   private ApplicationContext applicationContext;
   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
   }
    @ApolloConfigChangeListener
    private void onChange(ConfigChangeEvent changeEvent{
        refreshConfig(changeEvent.changedKeys());
    }
    private void refreshConfig(Set<String> changedKeys){
       System.out.println("将变更的参数更新到相应的对象中");
    }
}

十五. spring事务要如何避坑?

spring中的事务功能主要分为:声明式事务和编程式事务。

声明式事务

大多数情况下,我们在开发过程中使用更多的可能是声明式事务,即使用@Transactional注解定义的事务,因为它用起来更简单,方便。

只需在需要执行的事务方法上,加上@Transactional注解就能自动开启事务:

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Transactional
    public void add(UserModel userModel) {
        userMapper.insertUser(userModel);
    }
}

这种声明式事务之所以能生效,是因为它的底层使用了AOP,创建了代理对象,调用TransactionInterceptor拦截器实现事务的功能。

spring事务有个特别的地方:它获取的数据库连接放在ThreadLocal中的,也就是说同一个线程中从始至终都能获取同一个数据库连接,可以保证同一个线程中多次数据库操作在同一个事务中执行。

正常情况下是没有问题的,但是如果使用不当,事务会失效,主要原因如下:

除了上述列举的问题之外,由于@Transactional注解最小粒度是要被定义在方法上,如果有多层的事务方法调用,可能会造成大事务问题。

所以,建议在实际工作中少用@Transactional注解开启事务。

编程式事务

一般情况下编程式事务我们可以通过TransactionTemplate类开启事务功能。有个好消息,就是springboot已经默认实例化好这个对象了,我们能直接在项目中使用。

@Service
public class UserService {
   @Autowired
   private TransactionTemplate transactionTemplate;
   ...
   public void save(final User user) {
         transactionTemplate.execute((status) => {
            doSameThing...
            return Boolean.TRUE;
         })
   }
}

使用TransactionTemplate的编程式事务能避免很多事务失效的问题,但是对大事务问题,不一定能够解决,只是说相对于使用@Transactional注解要好些。

十六. 跨域问题的解决方案

关于跨域问题,前后端的解决方案还是挺多的,这里我重点说说spring的解决方案,目前有三种:

一.使用@CrossOrigin注解

@RequestMapping(“/user”)

@RestController

public class UserController {

@CrossOrigin(origins = "http://localhost:8016")
@RequestMapping("/getUser")
public String getUser(@RequestParam("name") String name) {
    System.out.println("name:" + name);
    return "success";
}

}

该方案需要在跨域访问的接口上加@CrossOrigin注解,访问规则可以通过注解中的参数控制,控制粒度更细。如果需要跨域访问的接口数量较少,可以使用该方案。

二.增加全局配置

@Configuration

public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("GET", "POST")
            .allowCredentials(true)
            .maxAge(3600)
            .allowedHeaders("*");
}

}

该方案需要实现WebMvcConfigurer接口,重写addCorsMappings方法,在该方法中定义跨域访问的规则。这是一个全局的配置,可以应用于所有接口。

三.自定义过滤器

@WebFilter("corsFilter")
@Configuration
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
}

该方案通过在请求的header中增加Access-Control-Allow-Origin等参数解决跨域问题。

顺便说一下,使用@CrossOrigin注解 和 实现WebMvcConfigurer接口的方案,spring在底层最终都会调用到DefaultCorsProcessor类的handleInternal方法:

最终三种方案殊途同归,都会往header中添加跨域需要参数,只是实现形式不一样而已。

十七. 如何自定义starter

以前在没有使用starter时,我们在项目中需要引入新功能,步骤一般是这样的:

  • 在maven仓库找该功能所需jar包
  • 在maven仓库找该jar所依赖的其他jar包
  • 配置新功能所需参数

以上这种方式会带来三个问题:

1.如果依赖包较多,找起来很麻烦,容易找错,而且要花很多时间。

2.各依赖包之间可能会存在版本兼容性问题,项目引入这些jar包后,可能没法正常启动。

3.如果有些参数没有配好,启动服务也会报错,没有默认配置。

「为了解决这些问题,springboot的starter机制应运而生」。

starter机制带来这些好处:

1.它能启动相应的默认配置。

2.它能够管理所需依赖,摆脱了需要到处找依赖 和 兼容性问题的困扰。

3.自动发现机制,将spring.factories文件中配置的类,自动注入到spring容器中。

4.遵循“约定大于配置”的理念。

在业务工程中只需引入starter包,就能使用它的功能,太爽了。

下面用一张图,总结starter的几个要素:

接下来我们一起实战,定义一个自己的starter。

第一步,创建id-generate-starter工程:

其中的pom.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <version>1.3.1</version>
    <groupId>com.sue</groupId>
    <artifactId>id-generate-spring-boot-starter</artifactId>
    <name>id-generate-spring-boot-starter</name>
    <dependencies>
        <dependency>
            <groupId>com.sue</groupId>
            <artifactId>id-generate-spring-boot-autoconfigure</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>
</project>

第二步,创建id-generate-spring-boot-autoconfigure工程:

该项目当中包含:

  • pom.xml
  • spring.factories
  • IdGenerateAutoConfiguration
  • IdGenerateService
  • IdProperties pom.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <version>1.3.1</version>
    <groupId>com.sue</groupId>
    <artifactId>id-generate-spring-boot-autoconfigure</artifactId>
    <name>id-generate-spring-boot-autoconfigure</name>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

spring.factories配置如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.sue.IdGenerateAutoConfiguration

IdGenerateAutoConfiguration类:

@ConditionalOnClass(IdProperties.class)
@EnableConfigurationProperties(IdProperties.class)
@Configuration
public class IdGenerateAutoConfiguration {
    @Autowired
    private IdProperties properties;
    @Bean
    public IdGenerateService idGenerateService() {
        return new IdGenerateService(properties.getWorkId());
    }
}

IdGenerateService类:

public class IdGenerateService {
    private Long workId;
    public IdGenerateService(Long workId) {
        this.workId = workId;
    }
    public Long generate() {
        return new Random().nextInt(100) + this.workId;
    }
}

IdProperties类:

@ConfigurationProperties(prefix = IdProperties.PREFIX)
public class IdProperties {
    public static final String PREFIX = "sue";
    private Long workId;
    public Long getWorkId() {
        return workId;
    }
    public void setWorkId(Long workId) {
        this.workId = workId;
    }
}

这样在业务项目中引入相关依赖:

<dependency>
      <groupId>com.sue</groupId>
      <artifactId>id-generate-spring-boot-starter</artifactId>
      <version>1.3.1</version>
</dependency>

就能使用注入使用IdGenerateService的功能了

@Autowired
  private IdGenerateService idGenerateService;

完美。

十八.项目启动时的附加功能

有时候我们需要在项目启动时定制化一些附加功能,比如:加载一些系统参数、完成初始化、预热本地缓存等,该怎么办呢?

好消息是springboot提供了:

  • CommandLineRunner
  • ApplicationRunner
    这两个接口帮助我们实现以上需求。

它们的用法还是挺简单的,以ApplicationRunner接口为例:

@Component
public class TestRunner implements ApplicationRunner {
    @Autowired
    private LoadDataService loadDataService;
    public void run(ApplicationArguments args) throws Exception {
        loadDataService.load();
    }
}

实现ApplicationRunner接口,重写run方法,在该方法中实现自己定制化需求。

如果项目中有多个类实现了ApplicationRunner接口,他们的执行顺序要怎么指定呢?

答案是使用@Order(n)注解,n的值越小越先执行。当然也可以通过@Priority注解指定顺序。

springboot项目启动时主要流程是这样的:

在SpringApplication类的callRunners方法中,我们能看到这两个接口的具体调用:

最后还有一个问题:这两个接口有什么区别?

CommandLineRunner接口中run方法的参数为String数组

ApplicationRunner中run方法的参数为ApplicationArguments,该参数包含了String数组参数 和 一些可选参数。


站在前人的肩膀上前行,才能使自己更快的成长,文章部分资源摘录网上,只针对部分知识进行了扩展,后续会详细增加其他内容。

文章来源:12345,6

记录自己学习的每一天;

相关文章
|
10月前
|
消息中间件 缓存 Java
Spring 代码优化技巧(大全2)(一)
Spring 代码优化技巧(大全2)
216 1
|
10月前
|
存储 前端开发 Java
Spring 代码优化技巧(大全1)(二)
Spring 代码优化技巧(大全1)
117 0
|
10月前
|
XML Java 数据库连接
Spring 代码优化技巧(大全1)(一)
Spring 代码优化技巧(大全1)
91 0
|
8天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
65 0
|
8天前
|
缓存 Java Maven
Spring Boot自动配置原理
Spring Boot自动配置原理
53 0
|
8天前
|
缓存 安全 Java
Spring Boot 面试题及答案整理,最新面试题
Spring Boot 面试题及答案整理,最新面试题
143 0
|
8天前
|
存储 JSON Java
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
50 2
|
8天前
|
前端开发 搜索推荐 Java
【Spring底层原理高级进阶】基于Spring Boot和Spring WebFlux的实时推荐系统的核心:响应式编程与 WebFlux 的颠覆性变革
【Spring底层原理高级进阶】基于Spring Boot和Spring WebFlux的实时推荐系统的核心:响应式编程与 WebFlux 的颠覆性变革
|
8天前
|
前端开发 Java 应用服务中间件
Springboot对MVC、tomcat扩展配置
Springboot对MVC、tomcat扩展配置
|
8天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例