Java 未实例化自动连线对象
我正在尝试做一个简单的应用程序,使用Spring和Hibernate保存用户。问题是控制器对象实例为null(我使用的是@Autowired) 我试着创建一个SpringUtils文件,设置一个作用域,设置@ComponentScan,但没有任何效果 Spring主要应用程序Java 未实例化自动连线对象,java,spring,hibernate,Java,Spring,Hibernate,我正在尝试做一个简单的应用程序,使用Spring和Hibernate保存用户。问题是控制器对象实例为null(我使用的是@Autowired) 我试着创建一个SpringUtils文件,设置一个作用域,设置@ComponentScan,但没有任何效果 Spring主要应用程序 @SpringBootApplication @EnableJpaRepositories @ComponentScan({"com.springprojectdao","com.springprojectc.contro
@SpringBootApplication
@EnableJpaRepositories
@ComponentScan({"com.springprojectdao","com.springprojectc.controller"})
@EntityScan("com.springprojectentity")
public class SpringProjectApplication {
@Autowired
static UserController userController; //it's null
public static void main(String[] args) {
SpringApplication.run(SpringProjectApplication.class, args);
userController.createUser();
}
}
控制器
@Controller
public class UserController {
@Autowired
private UserDAO userDAO;
//private UserVO user;
public UserVO initUser() {
UserVO user = new UserVO();
user.setUsername("Charly");
user.setPassword("alamo8");
user.setPhone("654789321");
return user;
}
//@Bean
public UserVO createUser() {
UserVO user = initUser();
userDAO.save(user);
return null;
}
}
刀
这是我得到的错误:
线程“main”java.lang.NullPointerException中出现异常
位于com.springproject.SpringProjectApplication.main(SpringProjectApplication.java)
在Springframework中,我们不能使它成为一个带有静态变量的Springbean。因为类加载器加载静态变量时未加载Spring上下文。因此,类加载器没有正确地将静态类注入bean,并且失败了
@Autowired
static UserController userController;
spring不能自动连接静态字段而不是静态变量,为什么不创建一个单例范围的bean呢?这是假设您想要一个静态变量的原因是,您想要在使用UserController的任何对象之间共享值。那么,我应该如何初始化对象?如果我使用静态变量的任何其他前缀,它会给我一个错误,为什么不创建一个单例范围的bean呢?这是假设您想要一个静态变量的原因是,您想要在使用UserController的任何对象之间共享值。
@Component
public class SpringUtils {
public static ApplicationContext ctx;
/**
* Make Spring inject the application context
* and save it on a static variable,
* so that it can be accessed from any point in the application.
*/
@Autowired
private void setApplicationContext(ApplicationContext
applicationContext) {
ctx = applicationContext;
}
}
@Autowired
static UserController userController;