方式一
直接在main方法中,根据SpringApplication.run()方法获取返回的Spring容最对象,再获取业务bean进行调用;
项目目录
- 创建一个Spring boot项目,不添加任何依赖。
- 创建一个接口层和它的实现层
接口层:
package com.wxw.service;
public interface HelloService {
public String Hello();
}
实现层:
package com.wxw.service.Imp;
import org.springframework.stereotype.Service;
import com.wxw.service.HelloService;
@Service
public class HelloServiceImp implements HelloService {
@Override
public String Hello() {
// TODO 自动生成的方法存根
return "Hello,Java";
}
}
- 在启动类中返回Spring容器对象,再获取业务bean进行调用。
package com.wxw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.wxw.service.HelloService;
@SpringBootApplication
public class SpringbootJavaApplication {
public static void main(String[] args) {
// 返回Spring容器对象
ConfigurableApplicationContext context = SpringApplication.run(SpringbootJavaApplication.class, args);
//getBean("helloServiceImp"),获取bean时必须开头字母小写
HelloService helloservice = (HelloService) context.getBean("helloServiceImp");
String s = helloservice.Hello();
System.out.println(s);
}
}
运行:
没有tomcat服务器
方式二
该方法是继承CommandLineRunner接口,覆盖CommandLineRunner接口的run()方法, run方法中编写具体的处理逻辑即可。
项目和上面的方式一一样
- 启动类继承CommandLineRunner接口,并实现它的方法run()。
- 添加HelloService接口,并@Autowired自动装配它。
- 在CommandLineRunner接口的run()方法中编写具体的处理逻辑
代码:
@SpringBootApplication
public class SpringbootJavaApplication implements CommandLineRunner {
@Autowired
private HelloService helloService;
public static void main(String[] args) {
SpringApplication.run(SpringbootJavaApplication.class, args);
}
/**
* 该方法相当于Java项目的main方法
*/
@Override
public void run(String... args) throws Exception {
//调用接口的方法并输出
System.out.println(helloService.Hello());
}
}
运行: