I'm trying to do a simple appliaction that saves a user using Spring and Hibernate. The problem is that the controller object instance is null (I'm using @Autowired).
I've tried to create a SpringUtils file, set a Scope, set @ComponentScan, but nothing worked.
Spring Main Application
@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
@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;
}
}
DAO
@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;
}
}
This is the error I get:
Exception in thread "main" java.lang.NullPointerException at com.springproject.SpringProjectApplication.main(SpringProjectApplication.java)