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?
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.
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.
@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.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With