What is the official spring boot method to run a simple Java application without the Internet?

I am involved in the processes of converting a simple java project to the spring boot option. The spring download reference guide http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/ was very useful overall, but most simple configuration examples include some web applications. An initial tutorial from The https://spring.io/guides/gs/spring-boot/ tutorial doesn't give the answer I'm looking for.

I have one HelloSpring class that I need to run one method on printHello() . For convenience, I have configured the following classes in one package:

Application.class

 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 

HelloConfiguration.class

 @Configuration public class HelloConfiguration { @Bean public HelloSpring helloSpring(){ HelloSpring hs = new HelloSpring(); hs.printHello(); hs.printHelloAgain(); return hs; } @Autowired public HelloSpring hs; } 

HelloSpring.class

 public class HelloSpring { public void printHello() { System.out.println("Hello Spring!"); } @PostConstruct public void printHelloAgain() { System.out.println("Hello Spring?"); } } 

It prints (spring logging omitted):

 Hello Spring! Hello Spring? Hello Spring? 

However, I am not sure about the correct way to execute my HelloSpring class.

Given the above example, what is the official way to connect and β€œstart” a class when loading spring?

+5
source share
2 answers

Just use ApplicationContext , which returns SpringApplication.run , and then works with that. That's almost all it takes

 public static void main(String[] args) { ApplicationContext context = SpringApplication.run(Application.class, args); HelloSpring bean = context.getBean(HelloSpring.class); bean.printHello(); } 

So you can open gui, etc. and use ApplicationContext to get beans, etc.

+5
source

From the docs: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-command-line-runner

Application.class

 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 

HelloSpring.class

 @Component public class HelloSpring implements CommandLineRunner { @Override public void run(String... args) { this.printHello(); } public void printHello() { System.out.println("Hello Spring!"); } } 

You can even make the run () method actually print your message, but in this way it comes closer to your intention when you implement the method and want it to be executed when the application starts.

+3
source

All Articles