Spring注解运行时抛出null

时间:2023-03-08 19:38:03

关于Spring的注解其实不难,大致需要以下几个流程:

一、配置Spring的注解支持

 <?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.ximesun.jee" />
<context:annotation-config /> </beans>

二、写对象时注解标识各种类,尽可能按照用途来区分

 @Controller
public class HomeAction {...}
@Service
public class HomeService {...}
@Repository
6 public class User {...}
7 @Component
8 public class MenuDao extends DbUtilsTemplate {...}

三、注解的注入和引用

 @Service
public class HomeService {
@Autowired
private MenuDao dao;
public List<Menu> getAllMenu(){
List<Menu> mlist = new ArrayList<Menu>();
mlist = dao.findAll();
return mlist;
}

OK,理论上这样就可以,然而很多时候会出现各种问题,例如我刚遇到这样一个抛出:

四、一个问题

 java.lang.NullPointerException
at com.ximesun.jee.fsdiserver.HomeService.getAllMenu(HomeService.java:20)
at com.ximesun.jee.fsdiserver.FSdiserver.main(FSdiserver.java:23)

JAVA的童鞋熟悉的不能再熟悉了吧~我确认相关的对象定义是没问题的,那引用呢?找到问题了:

 public static void main(String[] args) throws InterruptedException {
AbstractApplicationContext applicationContext = new FileSystemXmlApplicationContext(
"conf/context.xml");
List<Menu> mlist = new ArrayList<Menu>();
HomeService h = new HomeService();
mlist = h.getAllMenu();
applicationContext.registerShutdownHook();
}

问题就是这里new了HomeService,而new的类是不会根据注解自动引入的,那怎么办呢?

将上面的第五行代码修改为如下的方法初始化,问题就解决了。

 HomeService h = applicationContext.getBean("homeService",HomeService.class);

用Spring的环境里初始化这个对象,就可以顺理成章的使用这个对象中的关于Spring的注解了。

五、关于带参数的构造器的类的@AutoWired

首先这个类一定要有不带参数的构造器,然后就是要为构造器相关的参数写set方法。

错误的用法如下:

 @AutoWired
TcpClientSocketThread clientThread;
......
clientThread = new TcpClientSocketThread(id, clientSocket);
clientThread.start();

正确的用法如下:

 @AutoWired
TcpClientSocketThread clientThread;
......
clientThread.setClientId(id);
clientThread.setClientSocket(clientSocket);
clientThread.start();

更多关于Spring注解的内容和应用,建议参考《Spring in action》。