设为首页 加入收藏

TOP

结合springboot条件注入@ConditionalOnProperty以及@ConfigurationProperties来重构优化代码(二)
2023-07-25 21:23:08 】 浏览:74
Tags:结合 springboot @ConditionalOnProperty 以及 @ConfigurationProperties
*.jar的成员,继承@Component。

 

 

 

 

spring-context包里下面的这些注解,你一定知道。

+- context
| +- annotation
| | +- Bean
| | +- ComponentScan
| | +- Configuration
| | +- Import
| | +- Lazy
| | +- Primary
| | +- Profile
| | +- Scope
+- stereotype
| +- Service
| +- Component
| +- Controller
| +- Repository

而 @Value @Autowired 在 spring-beans-**.jar包里(package:org.springframework.beans.factory.annotation); @Mapping @PutMapping @ResponseBody @RestController etc., 在spring-web-**.jar包里(package:org.springframework.web.bind.annotation)。

 

BTW,@Service 与 @Component 的区别

 

再说改进项:@ConfigurationProperties取代@Value

org.springframework.boot.context.properties.ConfigurationProperties在spring-boot-**.jar里。用法很easy,指定prefix即可。
需要指明的是,setter方法还是要有的。这里使用lombok的@Setter注解。
其中,oemUserName与property配置项的名称不一致,需要单独用@Value指定,并且value必须用全名 : @Value("${smtp.config.oemName:null}")。

改造后的SmsUtil

package com.emax.zhenghe.common.util;
 
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
 
@Slf4j
//↓↓ 声明bean
@Configuration(value = "smsUtil")
@ConditionalOnProperty(prefix = "smtp.config", name = "requestAddress")
//↓↓ properties配置
@ConfigurationProperties(prefix = "smtp.config")
@Setter//必须有setter才能为field赋上值
public class SmsUtil {
    private String userName;
 
    private String requestAddress;
 
    private String password;
 
    @Value("${smtp.config.oemName:null}")
    private String oemUserName;
 
    private String oemPassWord;
 
    /**
     * 发送短信
     */
    public String sendSMS(String phone, String msg) {
        ...
    }
 
    /**
     * 发送短信
     */
    public String sendSMS(String phone, String msg,String userName,String passWord) {
        ...
    }
 
    /**
     * 发送短信
     */
    public String sendOemSMS(String phone, String msg, String smsSign) {
        ...
    }
}

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇配置环境变量 下一篇基本数据类型与引用类型在存储上..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目