开发者社区> 问答> 正文

Spring 使用 @Configuration配置:配置报错 

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

展开
收起
kun坤 2020-06-04 10:24:39 635 0
1 条回答
写回答
取消 提交回答
  •  */
    publicclassAppServer { 这个上面也需要有 注解  @service 或者 @Component ######回复 @waylau : AppServer 不用spring 管理 这个类里的spring 注解不会起作用的 你可以吧这个加入srping 容器 main 方法里启动spring 容器,然后从spring application context 获取这个类的实例######加了也没有用。我的是 new AppServer() 不需要 Spring 来管理、######你的 AppServer 没有用 spring 管理,当然不能把 MessageService 注入进去啊 ###### 你要用,当然不能 new,只能从 spring 容器里面获取,spring ClassPathXmlApplicationContext 可以从 classpath 上加载 xml 启动。 ######

    引用来自“李三石”的评论

     */
    publicclassAppServer { 这个上面也需要有 注解  @service 或者 @Component 三石哥正解! 我在  AppServer @Component 而后用 App 里面 改成下面就可以了。
    public static void main(String[] args) {
    		ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    		AppServer server = ctx.getBean(AppServer.class);
    		
    		server.run();
    				
    	}
    谢谢楼上2位
    2020-06-04 13:26:33
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载

相关实验场景

更多