在学习Spring 注解注入出现此问题
主要原因:这个注解不能写在局部变量,也就是不能写在方法体里,写外面去就好了
package com.bgu.edu;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
@Repository
public class TestDao {
@Test
public void testDao(){
@Autowired
UserService srevice;
User user = new User("002","里斯","正常");
srevice.addUser(user);
srevice.deleteUser(user);
}
}
然后报这个错误
解决后:
package com.bgu.edu;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
@Repository
public class TestDao {
@Autowired
UserService userService;
@Test
public void testDao(){
// ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
// UserService srevice = context.getBean("userService", UserService.class);
User user = new User("002","里斯","正常");
userService.addUser(user);
userService.deleteUser(user);
}
}