在春季订购评估条件注释

时间:2017-06-09 16:33:52

标签: java spring spring-boot spring-annotations operator-precedence

我有三个类,所有这些类都需要根据@ConditionalOnExpression注释启用/禁用。所有这些都在单独的.java文件中。

EX:

@ConditionalOnExpression("#T(com.xxx.xxx.xxx.xxx.CxProperties).isAEnabled()}")
Class A{
}


@ConditionalOnExpression("#T(com.xxx.xxx.xxx.xxx.CxProperties).isBEnabled()}")
Class B{
}


@ConditionalOnExpression("#T(com.xxx.xxx.xxx.xxx.CxProperties).isCEnabled()}")
Class C{
}

现在我在另一个类中有一个init函数,它首先被执行,我将启用/禁用值设置为类CxProperties。 注意:假设所有setter都是静态的

class setvalues{

        public void init(){
             /*Read config values from a file*/
             CxProperties.setAEnabled(true/false);
             CxProperties.setBEnabled(true/false);
             CxProperties.setCEnabled(true/false);
        }
}

现在,在没有设置启用/禁用的情况下,在程序开始时(甚至在执行init之前)会对这些条件进行评估。

春天是否有任何可能的方式来评估这些条件,例如在某个执行点之后对此进行评估?

任何指针都受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

我建议你不要使用@ConditionalOnExpression注释。

请考虑使用@PreAuthorize。是的,这是来自春天安全。

使用它可以保护每个服务不被使用,如果它没有启用,并为它动态切换启用/禁用状态:

@SpringBootApplication
public class So44462763Application {

    public static void main(String[] args) {
        SpringApplication.run(So44462763Application.class, args);
    }

    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)  // <-- this is required for PreAuthorize annotation to work
    public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
        }
    }

    interface CxProperties {
        boolean isServiceAEnabled();
        boolean isServiceBEnabled();
        boolean isServiceCEnabled();

        boolean enableService(String service);
        boolean disableService(String service);
    }

    @Component("cx")
    public static class CxPropertiesImpl implements CxProperties {
        private static final ConcurrentHashMap<String, Boolean> services = new ConcurrentHashMap<>(); //could be database/redis/property file/etc

        @PostConstruct
        private void init() {
            //services.put("serviceA", true); //initial population from property file/network resource/whatever
        }

        public boolean isServiceAEnabled() {
            return services.getOrDefault("serviceA", false);
        }

        public boolean isServiceBEnabled() {
            return services.getOrDefault("serviceB", false);
        }

        public boolean isServiceCEnabled() {
            return services.getOrDefault("serviceC", false);
        }
        //just a sample how you can dynamically control availability for each service
        @Override
        public boolean enableService(String service) {
            services.put(service, true);
            return services.getOrDefault(service, false);
        }

        @Override
        public boolean disableService(String service) {
            services.put(service, false);
            return services.getOrDefault(service, false);
        }
    }

    interface BusinessService {
        String doSomething();
    }

    @Service("serviceA")
    @PreAuthorize("@cx.serviceAEnabled")
    public static class ServiceA implements BusinessService {

        @Override
        public String doSomething() {
            return this.getClass().getSimpleName() + " doing some work";
        }
    }

    @Service("serviceB")
    @PreAuthorize("@cx.serviceBEnabled")
    public static class ServiceB implements BusinessService {

        @Override
        public String doSomething() {
            return this.getClass().getSimpleName() + " doing some work";
        }
    }

    @Service("serviceC")
    @PreAuthorize("@cx.serviceCEnabled")
    public static class ServiceC implements BusinessService {

        @Override
        public String doSomething() {
            return this.getClass().getSimpleName() + " doing some work";
        }
    }

    @RestController
    @RequestMapping("/api/work")
    public static class WorkApi {
        private static final Logger log = LoggerFactory.getLogger(WorkApi.class);

        private final List<BusinessService> businessServices;

        @Autowired
        public WorkApi(final List<BusinessService> businessServices) {
            this.businessServices = businessServices;
        }

        @GetMapping
        public String doWork() {
            final StringJoiner joiner = new StringJoiner(",");
            for (BusinessService service : businessServices) {
                try {
                    joiner.add(service.doSomething());
                } catch (AccessDeniedException e) {
                    log.warn("Service {} is disabled.", service);
                }
            }
            return joiner.toString();
        }
    }

    @RestController
    @RequestMapping("/api/control")
    public static class ControlApi {

        private final CxProperties cxProperties;

        @Autowired
        public ControlApi(final CxProperties cxProperties) {
            this.cxProperties = cxProperties;
        }

        @PostMapping("{service}/enable")
        public boolean enable(@PathVariable("service") String serviceName) {
            return cxProperties.enableService(serviceName);
        }

        @PostMapping("{service}/disable")
        public boolean disable(@PathVariable("service") String serviceName) {
            return cxProperties.disableService(serviceName);
        }
    }
}

这是一个示例用法:

$ curl -u user:123 -XGET 'localhost:8080/api/work'
$ curl -u user:123 -XPOST 'localhost:8080/api/control/serviceC/enable'
true% 
$ curl -u user:123 -XGET 'localhost:8080/api/work'                    
ServiceC doing some work%
$ curl -u user:123 -XPOST 'localhost:8080/api/control/serviceA/enable'
true%
$ curl -u user:123 -XGET 'localhost:8080/api/work'                    
ServiceA doing some work,ServiceC doing some work%

使用此方法即使不重新启动也可以控制服务的可访问性。

所有这一切都可以在没有弹簧安全的情况下完成,但涉及更多的手动工作,可能会略微降低代码的整体可读性。