1.前言
这里可以明显的看出来,之前我们创建的web应用中,resources目录下,都会有 static 和 templates 这两个目录,而这次创建的非web应用中,只有一个springboot的核心配置文件。
2.方式一
在 直接在 main 方法中,根据 SpringApplication.run() 方法获取返回的 Spring 容器对象,再获取业务 bean 进行调用。
2.1 创建一个业务接口和对应的实现类
package com.songzihao.springboot.service; /** * */ public interface StudentService { String sayHello(); }
package com.songzihao.springboot.service.impl; import com.songzihao.springboot.service.StudentService; import org.springframework.stereotype.Service; /** * */ @Service public class StudentServiceImpl implements StudentService { @Override public String sayHello() { return "Say Hello!!!"; } }
2.2 修改SpringBoot项目入口类
package com.songzihao.springboot; import com.songzihao.springboot.service.StudentService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class Application { public static void main(String[] args) { /** * SpringBoot程序启动后,返回值是ConfigurableApplicationContext,它也是一个Spring容器 * 它其实相当于原来Spring容器中的ClasspathXmlApplicationContext */ //获取SpringBoot容器 ConfigurableApplicationContext applicationContext=SpringApplication.run(Application.class, args); //从Spring容器中获取指定的对象 StudentService studentService= (StudentService) applicationContext.getBean("studentServiceImpl"); //调用业务方法 String str=studentService.sayHello(); System.out.println("str = " + str); } }
2.3 启动测试
3.方式二
Spring boot 的入口类实现 CommandLineRunner 接口
3.1 创建一个业务接口和实现类
package com.songzihao.springboot.service; /** * */ public interface StudentService { String sayHello(String msg); }
package com.songzihao.springboot.service.impl; import com.songzihao.springboot.service.StudentService; import org.springframework.stereotype.Service; /** * */ @Service public class StudentServiceImpl implements StudentService { @Override public String sayHello(String msg) { return "Say" + msg; } }
3.2 修改SpringBoot项目入口类
package com.songzihao.springboot; import com.songzihao.springboot.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private StudentService studentService; public static void main(String[] args) { SpringApplication.run(Application.class, args); } //重写CommandLineRunner接口中的run方法 @Override public void run(String... args) throws Exception { //调用业务方法 String str=studentService.sayHello("SpringBoot"); System.out.println("str = " + str); } }
3.3 启动测试