繁体   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