Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke repository method for standalone application?

I have following repository which extends jpa repositroy and also have an implementation class where i have autowired this.

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

@Service
public class ProjectServiceImpl {

@Autowired private ProjectDAO pDAO;

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

Now i have one Application.java class

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

configuration file

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

So how do we call this from main in case i dont to use any web based controller?

like image 281
Bhagwati Malav Avatar asked Jan 02 '26 02:01

Bhagwati Malav


1 Answers

This is a way:

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

Edit:

class Application {
    public static void main(String[] s){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersistenceContext.class);
        ProjectServiceImpl service = applicationContext.getBean(ProjectServiceImpl.class);
    }
}
like image 167
David Pérez Cabrera Avatar answered Jan 03 '26 17:01

David Pérez Cabrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!