简体   繁体   中英

Using Autowired bean inside Preauthorize expression in Spring

I have the following class for a resource in my Spring Application

@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.

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.

How can I achieve this?

If you want to define 2 bean implement same interface, then you can user annotation @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){...}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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