验证中...
Languages: Java
Categories: Web开发技术
Latest update 2018-12-06 22:18
gistfile1.txt
Raw Copy
springboot自动配置的原理是基于3个核心注解:@EnableAutoConfiguration,用于开启自动配置功能;
@Configuration表示进行配置bean;@ConditionalOnClass条件注解,某个类在工程中存在的条件下才允许自动配置。
基于这个原理,是可以模仿并自行实现自动配置的。
BeautyAutoConfig.java
Raw Copy
package com.demo.springbootdemo.autoconfigdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
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;
@Configuration
@EnableConfigurationProperties(BeautyProperties.class)
@ConditionalOnClass(BeautyService.class)
public class BeautyAutoConfig {
@Autowired
private BeautyProperties beautyProperties;
@Bean
public BeautyService generateBeautyService() {
BeautyService beautyService = new BeautyService();
beautyService.setName(beautyProperties.getName());
beautyService.setHeight(beautyProperties.getHeight());
beautyService.setCupSize(beautyProperties.getCupSize());
beautyService.setCellPhoneNumber(beautyProperties.getCellPhoneNumber());
System.out.println("beauty=" + beautyService);
return beautyService;
}
}
BeautyProperties.java
Raw Copy
package com.demo.springbootdemo.autoconfigdemo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "beauty")
@Data
public class BeautyProperties {
private String name;
private Integer height;
private String cupSize;
private String cellPhoneNumber;
}
BeautyService.java
Raw Copy
package com.demo.springbootdemo.autoconfigdemo;
import lombok.Data;
@Data
public class BeautyService {
private String name;
private Integer height;
private String cupSize;
private String cellPhoneNumber;
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

Gitee_you_jiang_zheng_wen Zheng_wen_close