1. 程式人生 > >SpringBoot入門(19)- 自定義starter

SpringBoot入門(19)- 自定義starter

1、具體用的類如下

RedisProperties.java

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix="redis")
public class RedisProperties {
	
	private String host;
	private Integer port;
	
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public Integer getPort() {
		return port;
	}
	public void setPort(Integer port) {
		this.port = port;
	}

}

RedisAutoConfiguration.java

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.Jedis;

@ConditionalOnClass(Jedis.class)
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public Jedis jedis(RedisProperties redisProperties){
		return new Jedis(redisProperties.getHost(), redisProperties.getPort());
	}
	
}

2、使用方法有兩種

方式一:自定義註解

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(RedisAutoConfiguration.class)
public @interface EnableJedis {

}
@EnableJedis
@SpringBootApplication
public class App 
{

方式二:利用spring.factories檔案配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.zemel.test.RedisAutoConfiguration