手写starter
rsa-spring-boot-starter
starter开发步骤:
1.新建一个Maven工程,引入starter开发需要的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>3.2.0</version>
</dependency>
2.编写提供服务的类、服务的属性配置类、服务的自动装配类
先写属性配置类:
@Data
@ConfigurationProperties(prefix = "qf.rsa")
public class RsaProperties {
/**
* rsa加密使用的安全码
*/
private String secure = "Java2024";
/**
* rsa加密使用的秘钥大小
*/
private int keySize = 512;
}
再写提供服务的类:
public class RsaService {
private final PublicKey publicKey;
private final PrivateKey privateKey;
public RsaService(RsaProperties properties) throws NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(properties.getKeySize(),new SecureRandom(properties.getSecure().getBytes()));
KeyPair keyPair = generator.genKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
}
/**
* 加密
* @param source 待加密字符串
* @return
*/
public String encrypt(String source) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] bytes = cipher.doFinal(source.getBytes());
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 解密
* @param encodeStr 待解密字符串
* @return
*/
public String decrypt(String encodeStr){
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
byte[] bytes = Base64.getDecoder().decode(encodeStr);
byte[] result = cipher.doFinal(bytes);
return new String(result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
然后写自动装配类:
@Configuration//这是一个用于自动配置的类
@EnableConfigurationProperties(RsaProperties.class)
@ConditionalOnClass(RsaService.class)//类路径下具有条件:存在RsaService类
public class RsaAutoConfig {
@Bean //当IOC容器中不存在RsaService的bean对象的时候,执行此方法创建对象放入ioc容器
@ConditionalOnBean(RsaService.class)
public RsaService rsaService(RsaProperties properties) throws NoSuchAlgorithmException {
return new RsaService(properties);
}
}
注意:当含有@Bean注解的方法中有参数,那么必须保证IOC容器中存在这个参数类型的bean对象,因为这里有@EnableConfigurationProperties注解,所以IOC容器中会创建RsaProperties对象。
3.在resources文件夹下新建一个META-INF文件夹,然后在这个文件夹下新建spring.factories文件,这个文件就是自动装配的配置文件。
org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.qf.rsaStarter.config.RsaAutoConfig
4.使用Maven的功能对工程进行打包(Lifecycle->install)
5.在其他工程中引用starter进行测试。