我正在尝试自动装配一个对象,但它变为空。我读过很多问题和答案,但仍然没有机会。这是我的Spring启动配置:
package com.alinso.fantasy;
import javax.persistence.EntityManagerFactory;
@SpringBootApplication
@ComponentScan({"com.alinso.fantasy","com.alinso.fantasy.database"})
@Configuration
public class FantasyApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(FantasyApplication.class, args);
}
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
以下是要自动装配的课程:
package com.alinso.fantasy.database;
@Service
public class BookDAO implements IBookDAO {
@Autowired
SessionFactory sessionFactory;
public UUID save(Book book){
Session session= sessionFactory.getCurrentSession();
session.saveOrUpdate(book);
return book.getId();
}
}
最后,这是我获得NPE的课程;
package com.alinso.fantasy.resource;
@Controller
public class BookResource {
@Autowired
private IBookDAO bookDao;
public void saveBook() {
Book b = new Book();
b.setBook_name("harry potter");
b.setPrice(50.00);
bookDao.save(b); // null pointer exception here
}
}
IBookDAO
界面;
package com.alinso.fantasy.database;
public interface IBookDAO {
public UUID save(Book book);
}
编辑:我从测试中调用控制器方法,如下所示:
public class BookResourceTest {
@Test
public void saveBook() {
BookResource bookResource = new BookResource();
bookResource.saveBook();
}
}
答案 0 :(得分:2)
在测试中,您必须为Spring定义运行程序以初始化@Autowired
变量。还要注意,您要注入的所有类都包含在组件扫描中。
此外,您可以跳过手动声明组件扫描的包命名,只需将包含@SpringBootApplication
的主SpringApp类注释到包结构的基础中,这将触发组件扫描&在该包裹下,check this。
有关how injection works on Spring的更多信息 并在testing in Spring Boot