Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring console application configured using annotations

I want to create spring console application (running from command line with maven for example: mvn exec:java -Dexec.mainClass="package.MainClass").

Is this application I want to have some kind of services and dao layers. I know how to do it for a web application but I have not found any information on how to do in case of a console application (leter maybe with Swing).

I'm trying to create something like:

public interface SampleService {  public String getHelloWorld(); }   @Service public class SampleServiceImpl implements SampleService {  public String getHelloWorld() {   return "HelloWorld from Service!";  } }  public class Main {  @Autowired  SampleService sampleService;  public static void main(String [] args) {   Main main = new Main();   main.sampleService.getHelloWorld();  } } 

Is it possible? Can I find somewhere an example of how to do it?

like image 798
fatman Avatar asked Jan 24 '11 22:01

fatman


People also ask

How do you do annotation based configuration in Spring?

Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider the following configuration file in case you want to use any annotation in your Spring application.

What is annotation @SpringBootApplication?

Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.

What is @configuration annotation used for?

@Configuration annotation indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.


1 Answers

Take a look at the Spring Reference, 3.2.2 Instantiating a container.

In order to use Spring in console application you need to create an instance of ApplicationContext and obtain Spring-managed beans from it.

Creating a context using XML config is described in the Reference. For completely annotation-based approach, you can do someting like this:

@Component // Main is a Spring-managed bean too, since it have @Autowired property public class Main {     @Autowired SampleService sampleService;     public static void main(String [] args) {         ApplicationContext ctx =              new AnnotationConfigApplicationContext("package"); // Use annotated beans from the specified package          Main main = ctx.getBean(Main.class);         main.sampleService.getHelloWorld();     } } 
like image 199
axtavt Avatar answered Sep 18 '22 05:09

axtavt