Spring MVC-如何动态加载/注入服务

时间:2019-02-11 09:17:24

标签: spring spring-mvc

对于我的Spring MVC应用程序,我将有一个控制器,该控制器将处理来自路径service/*的所有请求。 网址可以像 /service/item/getitems/service/property/getproperties

控制器将必须在运行时根据指定的URL加载服务类。例如,如果url为/service/item/getitems,则控制器应加载itemService并应能够调用itemService.getItems(); 如果网址为/service/property/getproperties,则应加载propertyService并调用propertyService.getProperties()

如何从控制器实现服务的运行时(动态)加载?

1 个答案:

答案 0 :(得分:0)

application.yml应该看起来像这样

server:
  port: 8090
  servlet:
    context-path: /service

ApiController.java应该看起来像这样

public abstract class ApiController<Id extends Serializable, E> {

    /**
     * Collection for service classes.
     *
     * @see AbstractService
     */
    private final AbstractService<Id, E> service;
    @Autowired
    private ApplicationContext appContext;

 public ApiController(AbstractService<Id, E> service) {
        this.service = service;
    }
    }

AbstractService.java应该看起来像这样

public interface AbstractService<Id extends Serializable, E> {

    /**
     *
     * @return
     */
    public default Class<E> getEntityClass() {
        return (Class<E>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];

    }

ItemController.java应该看起来像这样

@RestController
@RequestMapping(value = "/item")
public class ItemController extends ApiController<Integer, Item> {


private final ItemService itemService;

@Autowired
    public ItemController(ItemService service) {
    super(service);
    this.service = service;
    }
}

PropertyController.java应该看起来像这样

@RestController
@RequestMapping(value = "/property")
public class PropertyController extends ApiController<Integer, Property> {


private final PropertyService propertyService;

@Autowired
    public PropertyController(propertyService service) {
    super(service);
    this.service = service;
    }
}

这是您需要做的,以便获得所需的结果。