spring autowiring with processInjectionBasedOnCurrentContext(this);

前提是你 提交于 2019-12-25 01:18:27

问题


I have following situation. There is POJO which has autowired implementation of an interface, using some spring magic as shown bellow. However this dependency doesn't get resolved if creation of channels is managed via spring bean. It only works if POJO factory creates channels. Example bellow.

@Controller
public class Test{


    @RequestMapping(value = "/load", method = RequestMethod.GET)
    public @ResponseBody String testConfiguration() {

        // this is pojo and here it works, channels within have wired interface implementation                                          
        StaticFactory.getChannels(null);

        // if i call same method within spring managed bean (@Service) 
        // then it doesnt work


        System.out.println("channels created");

        return "alive";

    }

}

Created Channels are POJO but they have autowired interface implementation, which should be enabled with the following in constructor:

public DummyChannel() {

    // enables dependency injection of spring managed beans into POJO
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);    

}

public class StaticFactory {

    public static List<SmppChannel> getChannels(Map<ChannelMode, Integer> channelsDefinition) {

        List<SmppChannel> dummyChannels = new ArrayList<>();

        DummyChannel d = new DummyChannel();

        System.out.println("here");

        dummyChannels.add(new DummyChannel());

        return dummyChannels;
    }

}

Now, this thing works if i have non-spring managed Factory. Regardless if mentioned factory is static or not when it creates channels, they have properly wired interface implementation. However, if i copy paste exactly same code form the factory into Spring managed Bean annotated with @Service, wired dependency is null in created channel. Could somebody tell me what am i missing here, why things get injected when the factory of channels is not managed by the Spring ?

Edit Solution: // Okay, so the problem is in the fact that DummyChannels enable autowiring support in constructor while Spring beans are still not loaded. It is working if i do this within method that should access autowired service rather then the constructor of DummyChannel.


回答1:


Have you enabled annotation-config and component-scan in your xml or java configuration? Is the class that you want to inject annotated with @Service or @Resource?

Are you building a Web Service with JAX-WS? If yes, then I think your class (the one doing the autowiring) must implement SpringBeanAutowiringSupport so that Spring's IoC container can handle the injection.



来源:https://stackoverflow.com/questions/28656947/spring-autowiring-with-processinjectionbasedoncurrentcontextthis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!