java - Spring 4: NullPointerException during instantiation of ClassPathXmlApplicationContext -
i developing standalone spring 4 application, uses javafx. however, when try create new classpathxmlapplicationcontext
, autowired fields null, leading npes, though let spring instantiate classes.
this main class:
public class main extends application { public static void main(string[] args) { launch(); } public void start(stage stage) { configurableapplicationcontext context = new classpathxmlapplicationcontext("spring-config.xml"); gui gui = context.getbean(gui.class); stage.setscene(new scene(gui, 400, 400)); stage.show(); } }
this spring-config.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:annotation-config /> <context:component-scan base-package="org.my.package" /> </beans>
gui class:
@controller @scope("singleton") public class gui extends gridpane { @autowired private netmanager netmanager; @autowired private messengercomponent messenger; public gui() { netmanager.init("username"); ... } }
netmanager.class:
@service @scope("singleton") public class netmanager { ... }
the npe occurs before retrieve first bean, during creation of application context. idea why?
the order of injection following:
- constructor args
- fields
- setters/methods
under hood, spring (or di framework) create class calling constructor, , inject dependencies. can't use injected fields in constructor: injected after.
you should inject needed dependencies in constructor:
@autowired public gui(netmanager netmanager) { this.netmanager = netmanager; netmanager.init("username"); ... }
Comments
Post a Comment