Fixing BeanNotOfRequiredTypeException on Spring proxy cast on a non-singleton bean?

后端 未结 9 2093
走了就别回头了
走了就别回头了 2020-12-05 06:59

I\'m having an issue with pulling a Spring bean from an application context.

When I try;

InnerThread instance = (InnerThread) SpringContextFactory.g         


        
9条回答
  •  情书的邮戳
    2020-12-05 07:48

    One way to solve this issue is by extending the runnable interface and creating your own:

    public interface MyInterface extends Runnable {
      // your own method declarations here
      void doSomething();
      ...
    }
    

    Then you should implement your interface instead of the runnable:

    @Component("myInterface")
    @Scope("prototype")
         public class MyInterfaceImpl implements MyInterface {
    
              // your own method declarations here
              public void doSomething(){
              ...
              }
    
    
              // implement run from Runnable Interface
              @Transactional
              public void run(){
                    .....
              }
    
                 ...
            }
    

    This will work fine:

    ...
        MyInterface mynterface = SpringApplicationContext.getBean("myInterface", MyInterface.class);
    
        myInterface.doSomething();
      ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(myInterface);
    ...
    

提交回复
热议问题