【发布时间】:2019-07-26 11:50:28
【问题描述】:
我正在尝试做一个简单的应用程序来保存使用 Spring 和 Hibernate 的用户。问题是控制器对象实例为空(我使用的是@Autowired)。
我尝试创建一个 SpringUtils 文件,设置一个 Scope,设置 @ComponentScan,但没有任何效果。
Spring 主应用程序
@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;
}
}
道
@Repository
public interface UserDAO extends JpaRepository<UserVO,String> {
}
@Service
public class UserDAOImpl implements UserDAO {
@Override
public <S extends UserVO> S save(S entity) {
// TODO Auto-generated method stub
save(entity);
return null;
}
}
SpringUtils
@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;
}
}
这是我得到的错误:
线程“main”中的异常 java.lang.NullPointerException 在 com.springproject.SpringProjectApplication.main(SpringProjectApplication.java)
【问题讨论】:
-
spring 不能自动连接静态字段
-
为什么不创建一个单例范围的 bean,而不是静态变量?这是假设你想要一个静态变量的原因是你想要在使用你的 UserController 的任何东西之间共享值。