java - Spring 4 请求驱动的 Bean 创建

标签 java spring spring-mvc

我正在使用 Spring 4 (Spring Boot) 实现 Rest WS。

基本思想是我想使用指定标识符(例如社会安全号码或其他内容)的 JSON 有效负载并在该标识符上运行多个子服务。 这是一个示例有效负载:

{
    "ssNumber" : "1111111111111111",
    "subServicesDetails" :
    [
        { "subServiceName" : "Foo" , "requestParameters" : {} }, 
        { "subServiceName" : "Dummy", "requestParameters" : {} }
    ]
}

在我的代码中,我有多个“子服务”(FooServiceDummyService)实现 SubService 接口(interface):

package com.johnarnold.myws.service;

import com.johnarnold.myws.model.SubServiceDetails;

public interface SubService {

    public boolean service(String ssNumber, SubServiceDetails ssd);
}

下面是 FooService 代码。 包com.johnarnold.myws.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.johnarnold.myws.dao.FooDao;
import com.johnarnold.myws.model.Foo;
import com.johnarnold.myws.model.SubServiceDetails;

@Component
public class FooService implements SubService{
    private static Logger log = Logger.getLogger(FooService.class);

    @Autowired
    private FooDao dao;


    public FooService()
    {
        log.debug("FooService ctor");
    }


    public boolean service(String ssNumber, SubServiceDetails ssd)
    {
        log.debug("FooService service");

        Map <String, String> responseParameters = new HashMap<String, String>();
        try
        {
            Foo foo = dao.getFoo(ssNumber);
            if(foo.isCompromised())
            {
                responseParameters.put("listed", "true");
            }
            else
            {
                responseParameters.put("listed", "false");              
            }
            ssd.setResponseParameters(responseParameters);
            return true;
        }
        catch(Throwable ex)
        {
            log.error("Exception in service ", ex);
        }
        return false;
    }
}

现在我编写了自己的工厂来创建子服务,但是当我这样做时,当然是因为我在下面明确创建了我的bean(例如FooService) - 我的容器没有自动注入(inject)任何@Autowired成员 - 例如FooDao: 包 com.johnarnold.myws.service;

public class SubServiceFactory {

    /*
     * Instantiates a SubService for the supplied subServiceName or throws an exception if 
     * no valid SubService exists
     */
    public static SubService createSubService(String subServiceNameStr)
    {
        SubService subService = null;

        System.out.println("subServiceName [" + subServiceNameStr + "]");

        if(subServiceNameStr.equals("Foo"))
        {
            subService = new FooService();
        }
        if(subServiceNameStr.equals("Dummy"))
        {
            subService = new DummyService();
        }
        else
        {
            System.out.println("subServiceName [" + subServiceNameStr + "] is not defined");    
        }
        return subService;
    }
}

为了完整起见,这里是 Controller :

package com.johnarnold.myws.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.johnarnold.myws.model.RawsPayload;
import com.johnarnold.myws.model.SubServiceDetails;
import com.johnarnold.myws.service.SubService;
import com.johnarnold.myws.service.SubServiceFactory;
import com.johnarnold.myws.web.ValidMessage;

@RestController
@RequestMapping("/raws/")
public class RawsController {
    private static final Logger logger = Logger.getLogger(RawsController.class);    

    //@Autowired
    //SubService [] subSvcs;

    @RequestMapping(value="/{version}/status", method=RequestMethod.GET)
    public ResponseEntity<ValidMessage> getServiceStatus()
    {
        return new ResponseEntity<>(new ValidMessage() , HttpStatus.OK);
    }

    /*
     * Main entry point - orchestrates all of the WS Sub Services
     */
    @RequestMapping(value="/{version}/raws", method=RequestMethod.PUT)
    public ResponseEntity<String> raws(@Valid @RequestBody RawsPayload rawsPayload, 
            HttpServletRequest request)
    {
        logger.info("Request received");


        System.out.println("payl " + rawsPayload);

        System.out.println("ssNumber=" + rawsPayload.getSsNumber());
        System.out.println("sub svcs details=" + rawsPayload.getSubServicesDetails().length);

        SubServiceDetails[] subServiceDetails = rawsPayload.getSubServicesDetails();

        for(SubServiceDetails ssd : subServiceDetails)
        {

            String subServiceNameStr = ssd.getSubServiceName();

            System.out.println("svcname=" + subServiceNameStr);
            System.out.println("svc req params=" + ssd.getRequestParameters());
            System.out.println("svc resp params=" + ssd.getResponseParameters());

            SubService subService = SubServiceFactory.createSubService(subServiceNameStr);
            // Probably wrap the below with some timings
            subService.service(rawsPayload.getSsNumber(), ssd);
        }


        //System.out.println("svcs are " + subSvcs + "size=" + subSvcs.length);


        return new ResponseEntity<>("foo" , HttpStatus.OK);
    }

}

这是主要的有效负载类:

package com.johnarnold.myws.model;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.log4j.Logger;
import org.hibernate.validator.constraints.Length;

public class RawsPayload {
    static Logger log = Logger.getLogger(RawsPayload.class);

    @NotNull
    @Length(min=16, max=19)
    private String ssNumber;

    @Valid
    @NotNull
    @Size(min=1, max=3)
    private SubServiceDetails [] subServicesDetails;


    public String getSsNumber() {
        return ssNumber;
    }

    public void setSsNumber(String ssNumber) {
        log.info("setSsNumber()");
        this.ssNumber = ssNumber;
    }

    public SubServiceDetails[] getSubServicesDetails() {
        return subServicesDetails;
    }

    public void setSubServicesDetails(SubServiceDetails[] subServicesDetails) {
        this.subServicesDetails = subServicesDetails;
    }

}

我在 StackOverflow 上阅读了许多有关 Spring 4 Conditional Beans 的答案 - 但此功能似乎针对的是上下文/配置类型信息,而不是请求消息内容(如本例所示)。 谁能指出我正确的方向。如有必要,我可以提供进一步的背景信息 克罗格兹 约翰

最佳答案

解决此问题的两种可能方法:

  • 将所有子服务 bean 添加到 Spring 上下文中,然后使用 ServiceLocatorFactoryBean 从它们中进行选择。这是更好的方法(从体系结构的角度来看),但如果您以前从未使用过此概念,则可能需要更多时间来实现。

如果您想坚持使用基本的 Spring 解决方案,下面有一个更简单的替代方案:

  • 将子服务 bean 作为列表注入(inject)到主服务中,然后从中进行选择。它看起来像这样:

    @Bean public List<SubService> subServices(){ List<SubService> list = new SubService<>(); list.add(new AService()); list.add(new BService()); return list; }

然后

public SubService selectServiceByName() {
    //iterate through the list, pick the service with the right name and return - this solution will require you to bind by beannames
}

关于java - Spring 4 请求驱动的 Bean 创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540596/

相关文章:

spring - 如何阅读Spring框架源码?

java - 尝试将 JSON 数据发布到 Spring Controller ..根本不起作用

java - 使用 Java 将泰卢固语文本保存到 Oracle DB

java - 如何按集合大小总和对 Map<String, List<Set<Long>>> 进行排序?

spring - 使用 Spring : Method cannot be cast to Constructor 的 Jersey Singleton

Spring 集成: Send response to client http inbound gateway

java - 使用 JSR-250 (@RolesAllowed) 注释 Spring MVC 和容器身份验证

java - spring mvc 未定义名为 'springSecurityFilterChain' 的 bean

java - java中仅初始化数组的某些元素

java - Libgdx 在运行时更新纹理