SpringBoot--读取自定义配置文件
新建配置文件 custom-config.yaml
my-app:
auth-filter:
secretKey: mySecretKey
expirationTime: 864000000 # 10 天
excludes:
- /shore/demo/user/login
- /shore/demo/user/register
- /shore/demo/user/query
application.yaml 配置新文件路径
spring:
config:
import: classpath:custom-config.yaml
新建配置类映射配置属性
package com.shore.my_spring_demo.web.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "my-app.auth-filter")
@Data
public class CustomConfig {
private String secretKey;
private long expirationTime;
private List<String> excludes;
}
启动类配置 CustomConfig
可选,高版本SpringBoot 已经可以自动注入 @Compont 注解的类
package com.shore.my_spring_demo;
import com.shore.my_spring_demo.web.config.CustomConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(CustomConfig.class)
public class MySpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringDemoApplication.class, args);
}
}
使用
通过 @Resource 注解注入,然后就可以使用了
package com.shore.my_spring_demo.service.jwt;
import com.shore.my_spring_demo.common.enums.ErrorEnums;
import com.shore.my_spring_demo.exception.UsersException;
import com.shore.my_spring_demo.web.config.CustomConfig;
import com.shore.my_spring_demo.web.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.Date;
@Slf4j
@Service
public class JwtServiceImpl implements JwtService {
@Resource
private CustomConfig customConfig;
@Resource
private KeyPair keyPair;
.claim("sub", username)
.expiration(new Date(System.currentTimeMillis() + customConfig.getExpirationTime()))
.signWith(SignatureAlgorithm.RS256, keyPair.getPrivate())
.compact();
}
}
原文地址:https://blog.csdn.net/qq_35201802/article/details/143727005
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!