简体   繁体   English

在 Spring 中的 Preauthorize 表达式中使用 Autowired bean

[英]Using Autowired bean inside Preauthorize expression in Spring

I have the following class for a resource in my Spring Application我的 Spring 应用程序中有以下资源类

@RestController
@RequestMapping("/whatever")
public class SomeResource {

@Autowired
private CoolService coolService;

@RequestMapping(
            path = "",
            method = RequestMethod.GET)
    @PreAuthorize("hasPerm(@coolService.resolve(#attribute))")
    public void resource(@PathVariable("attribute") int attribute) {
        ...
    }

And I want to call the bean implementing CoolService that has been autowired by the Spring context, because for CoolService I have two beans that get activated depending on the profile at startup.我想调用由 Spring 上下文自动装配的实现CoolService的 bean,因为对于CoolService我有两个 bean,它们根据启动时的配置文件被激活。

public interface CoolService {

    resolve(int attribute);
}
@Service
@Profile("super")
public interface SuperCoolService implements CoolService {

    public Object resolve(int attribute){...}
}
@Service
@Profile("ultra")
public interface UltraCoolService implements CoolService {

    public Object resolve(int attribute){...}
}

However it seems that Spring does not know which bean to use because there is no single bean just named CoolService , and inside the Preauthorize I can't write @superCoolService or @ultraCoolService because it is profile-dependant.然而,Spring 似乎不知道要使用哪个 bean,因为没有一个名为CoolService bean,并且在Preauthorize我不能写@superCoolService@ultraCoolService因为它依赖于配置文件。

How can I achieve this?我怎样才能做到这一点?

If you want to define 2 bean implement same interface, then you can user annotation @Qualifier.如果你想定义 2 个 bean 实现相同的接口,那么你可以使用 @Qualifier 注释。 For example:例如:

@Service
@Qualifier("service1")
public interface SuperCoolService implements CoolService {

    public Object resolve(int attribute){...}
}

@Service
@Qualifier("service1")
public interface UltraCoolService implements CoolService {

    public Object resolve(int attribute){...}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM