个人学习Spring 手动装配之条件装配(二.接口编程实现)笔记

个人学习Spring 手动装配之条件装配(二.接口编程实现)笔记

话不多说,@Conditiional和实现Condition接口就可以了

show my code

package com.example.demo.bootstrap;

import com.example.demo.annotation.ConditionalOnSystemProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@Slf4j
public class ConditionOnSystemPropertyBootstrap {
    @Bean
    @ConditionalOnSystemProperty(name = "user.name",value = "yihan")
    public String helloWorld(){
        return "hello world 2019";
    }
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionOnSystemPropertyBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);
        String helloWorld = context.getBean("helloWorld", String.class);
        log.info("condition Success: result={}",helloWorld);
        context.close();
    }
}
package com.example.demo.annotation;

import com.example.demo.condition.ConditionOnSystemProperty;
import org.springframework.context.annotation.Conditional;

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR,ElementType.TYPE,ElementType.METHOD})
@Conditional(ConditionOnSystemProperty.class)
public @interface ConditionalOnSystemProperty {
    String name();
    String value();
}
package com.example.demo.condition;

import com.example.demo.annotation.ConditionalOnSystemProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

@Slf4j
public class ConditionOnSystemProperty implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
        String name = String.valueOf(annotationAttributes.get("name"));
        String value = String.valueOf(annotationAttributes.get("value"));
        String username = System.getProperty(name);
        log.info("name=[{}],value=[{}]",name,value);
        return value.equals(username);
    }
}

参考书籍:Sprinboot 编程思想

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值