如何为独立应用程序调用存储库方法?

时间:2017-07-28 11:32:42

标签: java spring spring-data-jpa

我有以下存储库,它扩展了jpa repositroy并且还有一个实现类,我已经自动装配了这个。

@Repository
public interface ProjectDAO extends CrudRepository<Project, Integer> {}

@Service
public class ProjectServiceImpl {

@Autowired private ProjectDAO pDAO;

public void save(Project p) { pDAO.save(p); } }

现在我有一个Application.java class

Class Application{
public static void main(String..s){
// I need a way to call a method of repository
}
}

配置文件

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories
@PropertySource("file:/Users/abc/Documents/application.properties")
public class PersistenceContext {
    @Autowired
    Environment environment;

那么如果我不使用任何基于Web的控制器,我们如何从main调用它?

1 个答案:

答案 0 :(得分:3)

这是一种方式:

class Application {
    public static void main(String[] s){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersistenceContext.class);
        ProjectDAO dao = applicationContext.getBean(ProjectDAO.class);
    }
}

编辑:

class Application {
    public static void main(String[] s){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersistenceContext.class);
        ProjectServiceImpl service = applicationContext.getBean(ProjectServiceImpl.class);
    }
}