第一种实现方法:
实现非web程序的主要步骤 :
1.编写一个service接口类,里面编写一个方法
public interface UserService {
public String sayHi(String name);
}
2.编写一个实现类,实现上面的接口:
@Service
public class UserServiceImpl implements UserService {
@Override
public String sayHi(String name) {
return "hi"+name;
}
}
3.在springboot运行类中,
SpringApplication.run(DubboProviderApplication.class, args);
这行代码的返回值是ConfigurableApplicationContext,这是spring的容器对象,提供设置活动和默认配置文件以及操作底层属性源的工具。
然后再从这个容器对象中获取bean,调用接口的方法即可。
ConfigurableApplicationContext context = SpringApplication.run(JavaApplication.class, args);
UserService userService = (UserService)context.getBean("userServiceImpl");
String s = userService.sayHi("springboot-java");
System.out.println(s);
这是控制台的输出:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-03-06 10:36:55.341 INFO 2276 --- [ main] com.springboot.java.JavaApplication : Starting JavaApplication on 大山 with PID 2276 (started by dell in D:\idea project\springboot-web)
2019-03-06 10:36:55.346 INFO 2276 --- [ main] com.springboot.java.JavaApplication : No active profile set, falling back to default profiles: default
2019-03-06 10:36:56.761 INFO 2276 --- [ main] com.springboot.java.JavaApplication : Started JavaApplication in 1.918 seconds (JVM running for 4.117)
hispringboot-java
第二种实现方法:
在第一种方法中做改动,修改main方法,得让这个类实现CommandLineRunner接口
@Autowired
private UserService userService;
@Override
public void run(String... args) throws Exception {
String sayHi = userService.sayHi("Spring Boot");
System.out.println(sayHi);
}
public static void main(String[] args) {
SpringApplication.run(JavaApplication.class,args);
}
这是控制台输出的:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-03-06 13:20:03.757 INFO 15268 --- [ main] com.springboot.java.JavaApplication : Starting JavaApplication on 大山 with PID 15268 (started by dell in D:\idea project\springboot-web)
2019-03-06 13:20:03.762 INFO 15268 --- [ main] com.springboot.java.JavaApplication : No active profile set, falling back to default profiles: default
2019-03-06 13:20:05.128 INFO 15268 --- [ main] com.springboot.java.JavaApplication : Started JavaApplication in 1.976 seconds (JVM running for 4.355)
hiSpring Boot