首页 > 解决方案 > 如何使用有效负载变量在 Springboots 中构造 @service

问题描述

我是春季靴子的新手,所以我希望这不是一个愚蠢的问题

我有一个@Service 需要启动一个类属性,这个属性需要一个来自Controller 中RestPayload 的信息。我没有找到最推荐的方法来做到这一点。

     @RestController
    public class UserController {

        @Autowired 
        private UserService userService;

        @RequestMapping("/searchUser")
        public List<UserWrapper> searchUser(@RequestBody UserWrapper userWrapper) {


            List<UserWrapper> returnUserWrapper = userService.findByName(userWrapper);
            return returnUserWrapper;
        }
}

而服务层,我想是这样的:

@Service
public class UserService {
    private LdapTemplate ldapTemplate;
    public static final String BASE_DN = "xxxxxxx";

    @Value( value = "${sample.ldap.url}" )
    private String ldapUrl;

    @Value( value =  "${sample.ldap.base}" )
    private String ldapBase;

    public UserService() {

    }

    public UserService(String dn, String password) {
        LdapContextSource ctxSrc = new LdapContextSource();
        System.out.println(this.ldapUrl);

        ctxSrc.setUrl(ldapUrl);
        ctxSrc.setBase(ldapBase);
        ctxSrc.setUserDn(dn);
        ctxSrc.setPassword(password);

        ctxSrc.afterPropertiesSet(); // this method should be called.\

        this.ldapTemplate =  new LdapTemplate(ctxSrc);

    }

字符串 dn 和字符串密码将来自 REST 有效负载,但其他属性来自属性文件。

希望有人可以用最佳实践指导我

标签: springspring-mvcspring-boot

解决方案


对于 ldap 身份验证,您应该查看 spring-security:

另一方面,您可以访问几乎任何请求参数,只需通过注释注入,如以下示例所示:


推荐阅读