目录
1 Spring Boot 框架中,创建一个非 Web 应用程序
1 Spring Boot 框架中,创建一个非 Web 应用程序
在 Spring Boot 框架中,要创建一个非 Web 应用程序(纯 Java 程序),有两种方式
方式一:直接在 main 方法中,根据 SpringApplication.run()方法获取返回的 Spring 容器对象,再获取业务 bean 进行调用。
方式二:Spring boot 的入口类实现 CommandLineRunner 接口
2 方式一
2.1 创建service接口和实现类
package com.liuhaiyang.springboot.service;
public interface StudentService {
String sayHello();
}
package com.liuhaiyang.springboot.service.impl;
import com.liuhaiyang.springboot.service.StudentService;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements StudentService {
@Override
public String sayHello() {
return "Say Hello!!!";
}
}
2.2 入口启动类
package com.liuhaiyang.springboot;
import com.liuhaiyang.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 方式二
3.1 创建service接口和实现类
package com.liuhaiyang.springboot.service;
public interface StudentService {
String sayHello(String msg);
}
package com.liuhaiyang.springboot.service.Impl;
import com.liuhaiyang.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 入口启动类
package com.liuhaiyang.springboot;
import com.liuhaiyang.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 SpringbootTest01Application implements CommandLineRunner {
@Autowired
private StudentService studentService;
public static void main(String[] args) {
SpringApplication.run(SpringbootTest01Application.class, args);
}
//重写CommandLineRunner接口中的run方法
@Override
public void run(String... args) throws Exception {
//调用业务方法
String str=studentService.sayHello("SpringBoot");
System.out.println("str = " + str);
}
}
3.3 结果截图