猿问

Spring自动连线声明的问题

我正在尝试按照 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 {

我正在运行带有声明的类测试


@Autowired

private static RepositoryContactService service;

和 main 方法中的代码


Contact contact = new Contact("handro1104@gmail.com", "handro");

service.save(contact);

问题在于“service.save(contact);”行 正在给我服务 null。


摇曳的蔷薇
浏览 130回答 3
3回答

米脂

从带有 @Service 注释的类只创建一个 bean,因为 @Service 的默认方式是 Singleton,因此您不需要静态地自动连接这些类 bean。改变:@Autowiredprivate static RepositoryContactService service;到 :@Autowiredprivate RepositoryContactService service;

FFIVE

Spring 无法自动装配 RepositoryContactService 的原因可能有很多。RepositoryContactService 不在@ComponentScan 中声明的包中。为此,尝试将存在 RepositoryContactService 和 ContactService 的包添加到@ComponentScan 的列表中。你已经写过你已经编写了类测试。如果它是单元测试类,则检查用于单元测试的所有注释是否存在。虽然这不会解决空问题,但我更喜欢编程而不是接口并使用限定符来告诉 spring 容器要注入哪个接口实现。
随时随地看视频慕课网APP

相关分类

Java
我要回答