为什么不在spring容器中调用@PostConstruct?

时间:2017-09-12 19:59:19

标签: spring spring-data-jpa

我试图在db shema中添加一些实体

配置:

@Configuration
@ComponentScan(ApplicationConfig.basePackage)
public class ApplicationConfig {
public final static String basePackage = "test"
}

spring容器调用:

public class StartApp {

public static void main(String... args) throws Exception{

    ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);

    TestEntityRepository repository = (TestEntityRepository) context.getBean("testEntityRepository");
    repository.save(new TestEntity("test"));
}

}

带注释的目标类:

public class PersistenceService {

@Autowired
TestEntityRepository testEntityRepository;

@PostConstruct
public void initialize(){
    //repository.deleteAll();

    testEntityRepository.save(new TestEntity("test1"));
    testEntityRepository.save(new TestEntity("test2"));
    testEntityRepository.save(new TestEntity("test3"));
}

}

因为表中只有一条记录 - “测试”。在Tomcat一切正常。

https://github.com/GlebSa/TestSpringJPA

1 个答案:

答案 0 :(得分:1)

您的PersistenceService似乎无法识别为服务。您可以将@Service添加到PersistenceService吗?

@Service
public class PersistenceService {
...
}

希望得到这个帮助。