Spring 使用 @Configuration配置, @Atowired 拿 bean 为null
如题。我用的是基于 Java 的 spring 配置,没有用到 xml, 但是 @Atowired 拿 bean 时,却是个null 值,求解脱,代码如下:
MessageService.java
package com.waylau.spring; import org.springframework.stereotype.Component; /** * 说明: * * @author <a href="http://www.waylau.com">waylau.com</a> 2015年4月13日 */ @Component public class MessageService { /** * */ public MessageService() { // TODO Auto-generated constructor stub } public String sayHi() { return "Hi, girl!"; } }
AppServer.java
package com.waylau.spring; import org.springframework.beans.factory.annotation.Autowired; /** * 说明: * * @author <a href="http://www.waylau.com">waylau.com</a> 2015年4月13日 */ public class AppServer { @Autowired private MessageService messageService; public void run() { System.out.println(messageService.sayHi()); } }
SpringConfig.java
package com.waylau.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * 说明:Spring 配置类 * * @author <a href="http://www.waylau.com">waylau.com</a> 2015年4月11日 */ @Configuration @ComponentScan(basePackages = "com.waylau.spring") public class SpringConfig { public SpringConfig() { // TODO Auto-generated constructor stub } }
App.java
package com.waylau.spring; public class App { public App() { // TODO Auto-generated constructor stub } public static void main(String[] args) { new AppServer().run(); } }
在 AppServer.java 中,那个 messageService 为 null
public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); AppServer server = ctx.getBean(AppServer.class); server.run(); }谢谢楼上2位
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。