当类对象是新的时,无法使用@spring注释
其实我有一个春季主要课程如下。
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
变为null。 任何人都可以给我一些解决方案,因为我也知道新的运营商不会为@autowired
工作。 因为我正在使用新实例加载类,所以只有它变为null。 任何人都可以指导我这件事
Spring有自己的方式为您提供新对象。 只要你使用@Autowired
和@Component/@Service/@Repository/@Controller
@Autowired
一致@Autowired
应该没有问题
由于所有“业务”对象实例化都由Spring处理,因此您永远不应该使用new
。 如果您没有其他方式获取实例(我真的怀疑它),您可以使用ApplicationContext.getBean()
但正如我所说,在大多数情况下,这不是必需的(这也是一个不好的做法)
如果您需要多个类的实例而不是注入它们(通过使用@Autowired
),您可以注入Provider
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[]{}); } }
在主类中添加特定服务bean。 只要服务在您的组件扫描包中,您就可以了。 不要使用新的操作员。
@Autowired private Specific specific;
如果你想利用自动assembly,那么我认为我们必须从春季来看。
您可以使用Beanutils创建一个新实例并使用支持弹簧特征的reflection。 请通过以下方法:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/BeanUtils.html