设为首页 加入收藏

TOP

SpringBoot自动装配初步认识(七)
2018-06-04 08:51:23 】 浏览:1048
Tags:SpringBoot 自动 装配 初步 认识
ON_BEAN_NAME));
            }
            if (containsDispatcherRegistrationBean) {
                return ConditionOutcome
                        .noMatch(message.found("non servlet registration bean").items(
                                DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
            }
            return ConditionOutcome.match(message.found("servlet registration beans")
                    .items(Style.QUOTE, registrations).append("and none is named "
                            + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
        }


        private ConditionMessage.Builder startMessage() {
            return ConditionMessage.forCondition("DispatcherServlet Registration");
        }


    }


}


该代码是创建SpringMvc的典型示例  我想@Bean @Configuration 这个大家在熟悉不过了,下面我们来看几个比较陌生的注解,我简单解释一下:


1.spring-boot利用Conditional来确定是否创建Bean实例,这个注解我们可以理解为满足一定条件我们才创建Bean


2.这些注解我们可以在spring-boot-autoconfigure-2.0.0.M7.jar下 org.springframework.boot.autoconfigure.condition下找到


3.常见的注解解释:


  3.1 @ConditionalOnBean :匹配给定的class类型或者Bean的名字是否在SpringBeanFactory中存在


  3.2 @ConditionalOnClass:匹配给定的class类型是否在类路径(classpath)中存在


  3.3 @ConditionalOnExpression : 匹配给定springEL表达式的值返回true时


  3.4 @ConditionalOnJava :匹配JDK的版本,其中range属性是枚举类型有两个值可以选择


      3.4.1 EQUAL_OR_NEWER 不小于


      3.4.2 OLDER_THAN 小于


                  3.4.3 value属性用于设置jdk版本


  3.5 ConditionalOnMissingBean:spring上下文中不存在指定bean时


    3.6 ConditionalOnWebApplication:在web环境下创建


@ConditionalOnBean is eva luated after all configuration classes have been processed, i.e you can't use it to make a whole configuration class conditional on the presence of another bean. You can, however, use it where you have to make all of the configuration's beans conditional on the presence of another bean.


注意:Conditional 只有在所有配置类被加载完的时候被评估是否要创建,因此Conditional不能在配置类里根据其他创建的方法进行判断


@Bean
@ConditionalOnBean({Teacher.class})
public Student student(StudentProperties studentProperties) {
    Student student = new Student();
    student.setStuName(studentProperties.getName());
    return student;
}


@Bean
@ConditionalOnMissingBean
public static Teacher teacher() {
    return new Teacher();
}


@Bean
@ConditionalOnMissingBean
public static School school() {
    return new School();
}
比如上述代码 Student是不会被创建的,如果非要@Bean和@Conditional使用,则可以借助于@Import方式实现
@Configuration
@EnableConfigurationProperties(StudentProperties.class)
@Import(TeacherAutoConfiguration.class)
public class MyTestAutoConfiguration {


    @Bean
    @ConditionalOnBean(Teacher.class)
    public Student student(StudentProperties studentProperties) {
        Student student = new Student();
       

首页 上一页 4 5 6 7 8 下一页 尾页 7/8/8
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇关于 SpringMVC+Spring+MyBatis .. 下一篇SpringBoot自动装配深入理解

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目