关于java:spring中让你眼前一亮的代码技巧

一. @Conditional的弱小之处

不晓得你们有没有遇到过这些问题:

  • 某个性能须要依据我的项目中有没有某个jar判断是否开启该性能。
  • 某个bean的实例化须要先判断另一个bean有没有实例化,再判断是否实例化本人。
  • 某个性能是否开启,在配置文件中有个参数能够对它进行管制。

如果你有遇到过上述这些问题,那么祝贺你,本节内容非常适合你。

@ConditionalOnClass

问题1能够用@ConditionalOnClass注解解决,代码如下:

public class A {
}

public class B {
}

@ConditionalOnClass(B.class)
@Configuration
public class TestConfiguration {

    @Bean
    public A a() {
      return new A();
    }
}
复制代码

如果我的项目中存在B类,则会实例化A类。如果不存在B类,则不会实例化A类。

有人可能会问:不是判断有没有某个jar吗?怎么当初判断某个类了?

直接判断有没有该jar下的某个要害类更简略。

这个注解有个升级版的利用场景:比方common工程中写了一个发消息的工具类mqTemplate,业务工程援用了common工程,只需再引入消息中间件,比方rocketmq的jar包,就能开启mqTemplate的性能。而如果有另一个业务工程,通用援用了common工程,如果不须要发消息的性能,不引入rocketmq的jar包即可。

这个注解的性能还是挺实用的吧?

@ConditionalOnBean

问题2能够通过@ConditionalOnBean注解解决,代码如下:

@Configuration
public class TestConfiguration {

    @Bean
    public B b() {
        return new B();
    }

    @ConditionalOnBean(name="b")
    @Bean
    public A a() {
      return new A();
    }
}
复制代码

实例A只有在实例B存在时,能力实例化。

@ConditionalOnProperty

问题3能够通过@ConditionalOnProperty注解解决,代码如下:

@ConditionalOnProperty(prefix = "demo",name="enable", havingValue = "true",matchIfMissing=true )
@Configuration
public class TestConfiguration {

    @Bean
    public A a() {
      return new A();
    }
}
复制代码

applicationContext.properties文件中配置参数:

demo.enable=false
复制代码

各参数含意:

  • prefix 示意参数名的前缀,这里是demo
  • name 示意参数名
  • havingValue 示意指定的值,参数中配置的值须要跟指定的值比拟是否相等,相等才满足条件
  • matchIfMissing 示意是否容许缺省配置。

这个性能能够作为开关,相比EnableXXX注解的开关更优雅,因为它能够通过参数配置是否开启,而EnableXXX注解的开关须要在代码中硬编码开启或敞开。

其余的Conditional注解

当然,spring用得比拟多的Conditional注解还有:ConditionalOnMissingClass、ConditionalOnMissingBean、ConditionalOnWebApplication等。

上面用一张图整体认识一下@Conditional家族。

自定义Conditional

说实话,集体认为springboot自带的Conditional系列曾经能够满足咱们绝大多数的需要了。但如果你有比拟非凡的场景,也能够自定义自定义Conditional。

第一步,自定义注解:

@Conditional(MyCondition.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
public @interface MyConditionOnProperty {
    String name() default "";

    String havingValue() default "";
}
复制代码

第二步,实现Condition接口:

public class MyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        System.out.println("实现自定义逻辑");
        return false;
    }
}
复制代码

第三步,应用@MyConditionOnProperty注解。

Conditional的神秘就藏在ConfigurationClassParser类的processConfigurationClass办法中:

这个办法逻辑不简单:

  1. 先判断有没有应用Conditional注解,如果没有间接返回false
  2. 收集condition到汇合中
  3. 按order排序该汇合
  4. 遍历该汇合,循环调用condition的matchs办法。

二. 如何妙用@Import?

有时咱们须要在某个配置类中引入另外一些类,被引入的类也加到spring容器中。这时能够应用@Import注解实现这个性能。

如果你看过它的源码会发现,引入的类反对三种不同类型。

然而我认为最好将一般类和@Configuration注解的配置类离开解说,所以列了四种不同类型:

一般类

这种引入形式是最简略的,被引入的类会被实例化bean对象。

public class A {
}

@Import(A.class)
@Configuration
public class TestConfiguration {
}
复制代码

通过@Import注解引入A类,spring就能主动实例化A对象,而后在须要应用的中央通过@Autowired注解注入即可:

@Autowired
private A a;
复制代码

是不是挺让人意外的?不必加@Bean注解也能实例化bean。

@Configuration注解的配置类

这种引入形式是最简单的,因为@Configuration注解还反对多种组合注解,比方:

  • @Import
  • @ImportResource
  • @PropertySource等。
public class A {
}

public class B {
}

@Import(B.class)
@Configuration
public class AConfiguration {

    @Bean
    public A a() {
        return new A();
    }
}

@Import(AConfiguration.class)
@Configuration
public class TestConfiguration {
}
复制代码

通过@Import注解引入@Configuration注解的配置类,会把该配置类相干@Import@ImportResource@PropertySource等注解引入的类进行递归,一次性全副引入。

因为文章篇幅无限不过多介绍了,这里留点悬念,前面会出一篇文章专门介绍@Configuration注解,因为它切实太太太重要了。

实现ImportSelector接口的类

这种引入形式须要实现ImportSelector接口:

public class AImportSelector implements ImportSelector {

private static final String CLASS_NAME = "com.sue.cache.service.test13.A";
    
 public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{CLASS_NAME};
    }
}

@Import(AImportSelector.class)
@Configuration
public class TestConfiguration {
}
复制代码

这种形式的益处是selectImports办法返回的是数组,意味着能够同时引入多个类,还是十分不便的。

实现ImportBeanDefinitionRegistrar接口的类

这种引入形式须要实现ImportBeanDefinitionRegistrar接口:

public class AImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(A.class);
        registry.registerBeanDefinition("a", rootBeanDefinition);
    }
}

@Import(AImportBeanDefinitionRegistrar.class)
@Configuration
public class TestConfiguration {
}
复制代码

这种形式是最灵便的,能在registerBeanDefinitions办法中获取到BeanDefinitionRegistry容器注册对象,能够手动管制BeanDefinition的创立和注册。

当然@import注解十分人性化,还反对同时引入多种不同类型的类。

@Import({B.class,AImportBeanDefinitionRegistrar.class})
@Configuration
public class TestConfiguration {
}
复制代码

这四种引入类的形式各有千秋,总结如下:

  1. 一般类,用于创立没有特殊要求的bean实例。
  2. @Configuration注解的配置类,用于层层嵌套引入的场景。
  3. 实现ImportSelector接口的类,用于一次性引入多个类的场景,或者能够依据不同的配置决定引入不同类的场景。
  4. 实现ImportBeanDefinitionRegistrar接口的类,次要用于能够手动管制BeanDefinition的创立和注册的场景,它的办法中能够获取BeanDefinitionRegistry注册容器对象。

ConfigurationClassParser类的processImports办法中能够看到这三种形式的解决逻辑:

最初的else办法其实蕴含了:一般类和@Configuration注解的配置类两种不同的解决逻辑。

三. @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数组 ApplicationRunnerrun办法的参数为ApplicationArguments,该参数蕴含了String数组参数一些可选参数

唠唠家常

写着写着又有这么多字了,依照常规,为了防止篇幅过长,明天就先写到这里。预报一下,前面会有AOP、BeanPostProcessor、Configuration注解等外围知识点的专题,每个主题的内容都挺多的,能够期待一下喔。

参考:《2020最新Java根底精讲视频教程和学习路线!》
链接:https://juejin.cn/post/693505…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理