method one
Directly in the main method to get the most capacity Spring objects returned by the SpringApplication.run () method, and then get the bean business calls;
project directory
- Spring boot create a project, do not add any dependencies.
- Create an interface layer and its implementation layer
Interface Layer:
package com.wxw.service;
public interface HelloService {
public String Hello();
}
Implementation layer:
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 return container object in the startup class, and then acquire the business bean call.
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);
}
}
Run:
no tomcat server
Second way
This method is inherited CommandLineRunner interface covering run CommandLineRunner interface () method, RUN method to prepare specific processing logic.
Projects and above as a way
- Start class inherits CommandLineRunner interface and implement its methods run ().
- Add HelloService interface and automated assembly @Autowired it.
- CommandLineRunner run in preparation of a specific interface, the processing logic () method
Code:
@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());
}
}
run: