本文共 4420 字,大约阅读时间需要 14 分钟。
给maven 的settings.xml配置文件的profiles标签添加
jdk‐1.8 true 1.8 1.8 1.8 1.8
★ idea中是自动集成springBoot插件
★ eclipse 需要安装一个spring ide
新建一个空白项目
新建一个maven quick-start模块
pom文件内容:
org.springframework.boot spring‐boot‐starter‐parent 2.2.2.RELEASE org.springframework.boot spring‐boot‐starter‐web org.springframework.boot spring‐boot‐maven‐plugin
启动代码
package com.demo.boot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * SpringBoot启动类: * 1、使用@SpringBootApplication * 2、提供应用程序的入口执行 * */@SpringBootApplicationpublic class App { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
追根溯源,Spring4演示(不再需要写配置文件)
Pom
4.0.0 com.boot.spring spring4-demo 1.0-SNAPSHOT spring4-demo http://www.example.com UTF-8 1.8 1.8 org.springframework spring-context 4.3.14.RELEASE junit junit 4.11 test maven-clean-plugin 3.0.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.7.0 maven-surefire-plugin 2.20.1 maven-jar-plugin 3.0.2 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2
User类
package com.boot.spring;import org.springframework.stereotype.Component;@Componentpublic class User {}
APP类(注解方式)
package com.boot.spring;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.boot.spring"); User user = context.getBean(User.class); System.out.println(user); context.close(); }}
使用@Configuration注解方式
package com.boot.spring;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class UseConfig { @Bean("user") public User createUser() { return new User(); }}
使用@Configuration注解方式后的app类
package com.boot.spring;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.boot.spring"); //@Component方式创建的对象,name默认为类名的首字母小写 User user = context.getBean("user",User.class); //@Configuration方式创建的对象,name默认为注解了 @Bean的方法名createUser,可以自定义名称:@Bean("user") //spring-boot的创建方式就是基于此实现的 User user1 = context.getBean("user",User.class); System.out.println(user+","+user1); //打印内容:com.boot.spring.User@5e57643e,com.boot.spring.User@5e57643e //单例实现方式:通过key-name值相同,对象相同的方式来实现 UseConfig useConfig = context.getBean(UseConfig.class); System.out.println(useConfig); //打印内容:com.boot.spring.UseConfig$$EnhancerBySpringCGLIB$$84f0eb4d@5e955596 context.close(); }}
转载地址:http://gyayz.baihongyu.com/