簡體   English   中英

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

[英]Using Autowired bean inside Preauthorize expression in Spring

我的 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) {
        ...
    }

我想調用由 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){...}
}

然而,Spring 似乎不知道要使用哪個 bean,因為沒有一個名為CoolService bean,並且在Preauthorize我不能寫@superCoolService@ultraCoolService因為它依賴於配置文件。

我怎樣才能做到這一點?

如果你想定義 2 個 bean 實現相同的接口,那么你可以使用 @Qualifier 注釋。 例如:

@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