我正在尝试按照 Petri Kainulainen 的“Spring Data”一书中的示例代码创建一个应用程序。我有一个服务 RepositoryContactService 包 com.packtpub.springdata.jpa.service;@Service("service")public class RepositoryContactService implements ContactService {我的 ApplicationContext 类设置了服务的包进行扫描@Configuration@ComponentScan(basePackages = { "com.packtpub.springdata.jpa.service" })@EnableTransactionManagement@EnableWebMvc@EnableJpaRepositories("com.packtpub.springdata.jpa.repository")@PropertySource("classpath:application.properties")public class ApplicationContext extends WebMvcConfigurerAdapter {我正在运行带有声明的类测试@Autowiredprivate static RepositoryContactService service;和 main 方法中的代码Contact contact = new Contact("handro1104@gmail.com", "handro");service.save(contact);问题在于“service.save(contact);”行 正在给我服务 null。
3 回答

米脂
TA贡献1836条经验 获得超3个赞
从带有 @Service 注释的类只创建一个 bean,因为 @Service 的默认方式是 Singleton,因此您不需要静态地自动连接这些类 bean。
改变:
@Autowired
private static RepositoryContactService service;
到 :
@Autowired
private RepositoryContactService service;

FFIVE
TA贡献1797条经验 获得超6个赞
Spring 无法自动装配 RepositoryContactService 的原因可能有很多。
RepositoryContactService 不在@ComponentScan 中声明的包中。为此,尝试将存在 RepositoryContactService 和 ContactService 的包添加到@ComponentScan 的列表中。
你已经写过你已经编写了类测试。如果它是单元测试类,则检查用于单元测试的所有注释是否存在。
虽然这不会解决空问题,但我更喜欢编程而不是接口并使用限定符来告诉 spring 容器要注入哪个接口实现。
添加回答
举报
0/150
提交
取消