簡體   English   中英

類對象為新對象時無法使用@spring批注

[英]Unable to use @spring annotations when class object is new

實際上,我的春季主要課程如下。

ClassLoader loader = null;

    try {
        loader = URLClassLoader.newInstance(new URL[]{new   

 File(plugins + "/" + pluginName + "/" + pluginName +   

 ".jar").toURI().toURL()}, getClass().getClassLoader());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

 Class<?> clazz = null;

    try {

        clazz = Class.forName("com.sample.Specific", true, loader);

    } catch (ClassNotFoundException e) {

        e.printStackTrace();

    }

Method method = null;
    try {
        method = clazz.getMethod("run",new Class[]{});
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

 try {
        method.invoke(clazz.newinstance,new Object[]{});
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

具體類別如下:

package com.sample
@Service
public class Specific {

    @Autowired
    private FD fd;


    public void run(){

        fd.init();

    }

}

@Autowired FD為空。 誰能給我一些解決方案,因為我也知道新的運算符不適用於@autowired 當我用新實例加載類時,只有它變為空。 誰能在這件事上指導我

在您的主類中添加特定服務bean。 只要該服務位於組件掃描包中,就可以了。 不要使用新的運算符。

@Autowired
private Specific specific;

Spring有自己的方式為您提供新對象。 只要您使用@Autowired@Component/@Service/@Repository/@Controller保持一致,就不會有問題

而且由於所有“業務”對象實例化都是由Spring處理的,因此您永遠不要使用new 如果您沒有其他獲取實例的方式(對此我真的很懷疑),則可以使用ApplicationContext.getBean()但正如我所說,在大多數情況下,這不是必需的(這也是一種不好的做法)

如果您需要一個類的多個實例而不是注入它們(通過使用@Autowired ),則可以注入Provider<T>

UPDATE

由於該類在運行時是已知的,因此您需要注入ApplicationContext並使用它來獲取bean:

public class TheClassWhereYouAreCreatingTheObject {

    @Autowired
    private ApplicationContext context;                  // You definitely need this

    public void theMethodWhereYouAreCreatingTheObject() {
         Class<?> clazz = ...                            // getting the object class
         Object instance = context.getBean(clazz);     // getting and instance trough Spring

         // If you know that kind of object you will get cast it at call its methods
         ((Specific) instance).run();

         // If you know anything about the class you will have to use reflection
         Method method = clazz.getMethod("run", new Class[]{});
         method.invoke(instance, new Object[]{});
    }
}

如果您想利用自動裝配的優勢,那么我認為我們必須從春季開始考慮。

您可以使用Beanutils創建一個新實例,並使用支持Spring功能的反射進行播放。 請通過以下方法:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/BeanUtils.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM