以 HttpEncodingAutoConfiguration 为例子
@Configuration( //这是一个配置类
proxyBeanMethods = false
)
@EnableConfigurationProperties({ServerProperties.class}) //开启指定类的自动配置,并把ServerProperties加入到ioc容器中
//spring底层的@Conditional,根据不同的条件,满足指定的条件,配置类才会生效;
@ConditionalOnWebApplication( //判断当前应用是否是web应用,是,配置类就生效
type = Type.SERVLET
)
//CharacterEncodingFilter是springmvc中解决乱码的类
@ConditionalOnClass({CharacterEncodingFilter.class}) //判断当前项目有没有这个类
@ConditionalOnProperty( //判断配置文件中是否存在某个配置
prefix = "server.servlet.encoding",
value = {"enabled"},
matchIfMissing = true //如果不存在,也是成立的
)
public class HttpEncodingAutoConfiguration {
private final Encoding properties;
//只要一个参数的情况下,参数的值就会从容器中拿
public HttpEncodingAutoConfiguration(ServerProperties properties) {
this.properties = properties.getServlet().getEncoding();
}
//给容器中添加一个组件,这个组件的某个值需要从配置文件properties中获取
@Bean
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
return filter;
}
进入 ServerProperties 类
@ConfigurationProperties( //根据配置文件自动装配值和bean属性
prefix = "server",
ignoreUnknownFields = true
)
public class ServerProperties {
private Integer port;
private InetAddress address;
@NestedConfigurationProperty
private final ErrorProperties error = new ErrorProperties();
private ServerProperties.ForwardHeadersStrategy forwardHeadersStrategy;
private String serverHeader;
private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8L);
private Shutdown shutdown;
@NestedConfigurationProperty
private Ssl ssl;
@NestedConfigurationProperty
private final Compression compression;
@NestedConfigurationProperty
private final Http2 http2;
private final ServerProperties.Servlet servlet;
private final ServerProperties.Tomcat tomcat;
private final ServerProperties.Jetty jetty;
private final ServerProperties.Netty netty;
private final ServerProperties.Undertow undertow;
大致思路很像我之前的写的配置文件的自动装配一文,哈哈