"Spring Boot Framework entry to practice" (19) Spring Boot pure Java development project

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
Here Insert Picture Description

  1. Spring boot create a project, do not add any dependencies.
  2. 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";
	}

}

  1. 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:
Here Insert Picture Description
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

  1. Start class inherits CommandLineRunner interface and implement its methods run ().
  2. Add HelloService interface and automated assembly @Autowired it.
  3. 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:
Here Insert Picture Description

Published 24 original articles · won praise 10 · views 734

Guess you like

Origin blog.csdn.net/qq_43581078/article/details/103946681