中山英文网站建设手表商城网站建设方案
web/
2025/9/28 10:50:44/
文章来源:
中山英文网站建设,手表商城网站建设方案,百度福州分公司,菏泽建设局网站SpringBoot用来简化Spring应用开发#xff0c;约定大于配置#xff0c;去繁从简#xff0c;是由Pivotal团队提供的全新框架。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置#xff08;有特殊需求可以添加自己的配置覆盖默认配…SpringBoot用来简化Spring应用开发约定大于配置去繁从简是由Pivotal团队提供的全新框架。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置有特殊需求可以添加自己的配置覆盖默认配置从而使开发人员不再需要定义样板化的配置。SpringBoot可以看成是J2EE的一站式解决方案。
一、SpringBoot 的优点
【1】快速创建独立运行的Spring项目以及与主流框架集成。 【2】使用嵌入式的Servlet容器应用无需打成war包可以打成jar包通过java -jar的方式直接运行。 【3】starters启动器自动依赖与版本控制。 【4】大量的自动配置简化开发也可以修改默认值。 【5】无需配置XML无代码生成开箱即用。 【6】准生产环境的运行时应用监控。 【7】与云计算的天然集成。
二、解决微服务部署和运维难的问题Spring Boot 如上的流程依次为 搭建项目 构建连接 批处理
三、Spring Boot 入门项目 HelloWorld也可以参考五快速创建一个 SpringBoot项目 【1】准备环境 为Maven的settings.xml配置文件的profiles标签添加如下信息
profile
idjdk-1.8/id
activationactiveByDefaulttrue/activeByDefaultjdk1.8/jdk
/activation
propertiesmaven.compiler.source1.8/maven.compiler.sourcemaven.compiler.target1.8/maven.compiler.targetmaven.compiler.compilerVersion1.8/maven.compiler.compilerVersion
/properties
/profile【2】将IDEA的 Maven更换为我们自己本地安装的Maven。自行百度更换创建一个maven工程[jar]在pom.xml中导入如下依赖
parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.0.0.RELEASE/version
/parent
dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency
/dependencies【3】编写一个主程序启动SpringBoot应用
SpringBootApplication
public class Hello {public static void main(String[] args) throws Exception {//启动spring应用SpringApplication.run(Hello.class, args);}
}【4】编写相关的Controller、Service类
Controller
public class HelloController {ResponseBodyRequestMapping(/hello)public String hello(){return hello world!;}
}【5】运行主测试程序。简化部署应用可以将应用打包成一个可执行的jar包通过Maven Projects中 的package双击即可。生成jar的位置默认在项目的target目录下的“项目名称.jar”文件。运行jar在命令行可以通过 “java -jar jar文件名.jar” 命令运行项目。
buildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/plugin/plugins
/build四、Hello World 探究POM文件
【1】父项目[spring-boot-starter-parent]
parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.0.0.RELEASE/version
/parent【2】进入spring-boot-starter-parent发现它还有一个父项目
parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-dependencies/artifactIdversion2.0.0.RELEASE/versionrelativePath../../spring-boot-dependencies/relativePath
/parent【3】进入spring-boot-dependencies后发现如下信息与之前我们创建的分布式项目继承的Maven父项目功能是一样的用来管理所有jar包依赖的版本。称为SpringBoot的版本仲裁中心以后我们导入依赖默认是不需要写版本没有在dependencies里面管理的依赖需要声明版本号
propertiesactivemq.version5.15.3/activemq.versionantlr2.version2.7.7/antlr2.versionappengine-sdk.version1.9.62/appengine-sdk.versionartemis.version2.4.0/artemis.versionaspectj.version1.8.13/aspectj.versionassertj.version3.9.1/assertj.version... 此处省略 .../
/properties【4】启动器[spring-boot-starter-web]
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId
/dependencyspring-boot-starter-webspring-boot-starter指spring-boot场景启动器进入官网可以到有许多场景启动器简单点说就是通过此功能将相关jar包给组合在起来我们使用时只需要引入一个Web Starter就可以轻松搞定。Spring Boot将所有的功能场景都抽取出来做成一个个的 starters启动器只需要在项目里面引入这些starter相关场景所有依赖都会导入进来。要用什么功能就导入什么场景启动器。 点击web右边的pom可以看到SpringBoot为我们依赖的其它jar包帮我们导入了web模块正常运行所依赖的所有组件。如下
dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-tomcat/artifactId/dependencydependencygroupIdorg.hibernate/groupIdartifactIdhibernate-validator/artifactId/dependencydependencygroupIdcom.fasterxml.jackson.core/groupIdartifactIdjackson-databind/artifactId/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-web/artifactId/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-webmvc/artifactId/dependency
/dependencies【5】主程序类Java类SpringBootApplication此注解声明的类是SpringBoot的主配置类SpringBoot就应该运行这个类的main方法来启动SpringBoot。
//ImportResource(locations{classpath:bean.xml})
//SpringBootApplication 来标注一个主程序类说明这是一个SpringBoot应用
SpringBootApplication
public class HellowordQuickStartApplication {public static void main(String[] args) {/*SpringBoot应用启动项HellowordQuickStartApplication.class 参数必须是用SpringBootApplication注解修饰的类*/SpringApplication.run(HellowordQuickStartApplication.class, args);}
}SpringBootApplication主要由SpringBootConfiguration/EnableAutoConfiguration/ComponentScan组成
Target(ElementType.TYPE)
Retention(RetentionPolicy.RUNTIME)
Documented
Inherited
SpringBootConfiguration
EnableAutoConfiguration
ComponentScan(excludeFilters {Filter(type FilterType.CUSTOM, classes TypeExcludeFilter.class),Filter(type FilterType.CUSTOM, classes AutoConfigurationExcludeFilter.class) })
public interface SpringBootApplication {SpringBootConfiguration标注在某个类上表示此类是一个SpringBoot的配置类。由以下注解组合形成配置类 配置文件配置类也是容器的一个组件底层由Component等等组成。
Target({ElementType.TYPE})
Retention(RetentionPolicy.RUNTIME)
Documented
Configuration //表示此类是一个配置类 是spring的一个组件
public interface SpringBootConfiguration {EnableAutoConfiguration开启自动配置功能。也是一个组合注解由以下注解组成部分重要注解
AutoConfigurationPackage
Import(AutoConfigurationImportSelector.class)
public interface EnableAutoConfiguration {AutoConfigurationPackage自动依赖相关的配置包也是一个组合注解主要由import等注解组合
Import({Registrar.class})//给容器中导入一个组件导入的组件由此组建决定。
public interface AutoConfigurationPackage {进入Import(Registrar.class)中的Registrar类中通过断点可以查看到我注释的一些信息。
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {Registrar() {}//registerBeanDefinitions方法中的metadata可以查看到我们启动类使用的注解 SpringBootApplicationpublic void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {AutoConfigurationPackages.register(registry, new String[]{(new AutoConfigurationPackages.PackageImport(metadata)).getPackageName()});}//new AutoConfigurationPackages.PackageImport(metadata) 可以解析出我们当前主启动所在的package包public SetObject determineImports(AnnotationMetadata metadata) {return Collections.singleton(new AutoConfigurationPackages.PackageImport(metadata));}
}Import(Registrar.class)作用将主配置类的所在包以及下边所有子包里面的所有组件扫描到Spring容器中。这也就能理解为什么会自动扫描我们写的Controller类了。 Import(AutoConfigurationImportSelector.class)进入AutoConfigurationImportSelector.class类中查看如下方法
public String[] selectImports(AnnotationMetadata annotationMetadata) {if(!this.isEnabled(annotationMetadata)) {return NO_IMPORTS;} else {try {AutoConfigurationMetadata autoConfigurationMetadata AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);AnnotationAttributes attributes this.getAttributes(annotationMetadata);// 主要用到的是 这个 configurations 后面会有重点说明ListString configurations this.getCandidateConfigurations(annotationMetadata, attributes);configurations this.removeDuplicates(configurations);configurations this.sort(configurations, autoConfigurationMetadata);SetString exclusions this.getExclusions(annotationMetadata, attributes);this.checkExcludedClasses(configurations, exclusions);configurations.removeAll(exclusions);configurations this.filter(configurations, autoConfigurationMetadata);this.fireAutoConfigurationImportEvents(configurations, exclusions);return StringUtils.toStringArray(configurations);} catch (IOException var6) {throw new IllegalStateException(var6);}}
}这是导入组件的选择器方法将所有需要导入的组件以全类名的方式返回这些组件最终被添加到容器中。其中ListString configurations会给容器中导入非常多的自动配置类[xxxAutoConfiguration]就是给容器中导入这个场景需要的所有组件并配置好这些组件。有了自动配置类免去了我们手动编写配置注入功能组件等的工作自动配置类共109个如下部分所示 ☹ 那么我们就有疑问这些自动配置类都是从哪里来的 进入这个方法this.getCandidateConfigurations(annotationMetadata, attributes)
protected ListString getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {// *** 后边需要了解的方法 ***//SpringFactoriesLoader.loadFactoryNamesEnableAutoConfiguration.class,classLoader;ListString configurations SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());Assert.notEmpty(configurations, No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.);return configurations;
}进入SpringFactoriesLoader.loadFactoryNamesEnableAutoConfiguration.class,classLoader方法具体注释说明
public static ListString loadFactoryNames(Class? factoryClass, Nullable ClassLoader classLoader) {//org.springframework.context.ApplicationContextInitializerString factoryClassName factoryClass.getName();return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
private static MapString, ListString loadSpringFactories(Nullable ClassLoader classLoader) {MultiValueMapString, String result (MultiValueMap)cache.get(classLoader);if(result ! null) {return result;} else {try {//通过类加载器classLoader获取META-INF/spring.factories也就是配置了109个自动配置类的文件 资源EnumerationURL urls classLoader ! null?classLoader.getResources(META-INF/spring.factories):ClassLoader.getSystemResources(META-INF/spring.factories);LinkedMultiValueMap result new LinkedMultiValueMap();while(urls.hasMoreElements()) {URL url (URL)urls.nextElement();UrlResource resource new UrlResource(url);//将urls 当做一个properties配置文件Properties properties PropertiesLoaderUtils.loadProperties(resource);Iterator var6 properties.entrySet().iterator();while(var6.hasNext()) {Entry?, ? entry (Entry)var6.next();//将META-INF/spring.factories文件中的EnableAutoConfiguration下的配置进行加载 如下图所示ListString factoryClassNames Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));result.addAll((String)entry.getKey(), factoryClassNames);}}cache.put(classLoader, result);return result;} catch (IOException var9) {throw new IllegalArgumentException(Unable to load factories from location [META-INF/spring.factories], var9);}}
}我们进入其中一个自动配置类中看看SpringBoot是不是真的帮我们已经配置好了一些属性[WebMvcAutoConfiguration]
//这里我就摘出一些重要的配置来帮我我们观察即可。
Configuration
public class WebMvcAutoConfiguration {BeanConditionalOnMissingBean/** 视图解析器 SpringBoot中的所有配置文件都是.java形式方法的名字就是以前xml中的id。等等都是用注解表示的这个我们后面会重点说明这里就先了解一下*///我们可以看到SpringBoot已经帮我们配置好了视图解析器 等等一些功能 我们直接使用就好public InternalResourceViewResolver defaultViewResolver() {InternalResourceViewResolver resolver new InternalResourceViewResolver();resolver.setPrefix(this.mvcProperties.getView().getPrefix());resolver.setSuffix(this.mvcProperties.getView().getSuffix());return resolver;}
}总结 SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值将这些值作为自动配置类导入到容器中自动配置类就生效帮我们进行自动配置工作。如此一来就具有我们在SSM等环境下写了一大堆配置文件后才具有的功能。而这些所有配置文件都在spring-boot-autoconfigure-2.0.0.RELEASE.jar 中。
五、使用 Spring Initializer 快速创建 Spring Boot 项目 注意Artifact中不能大小写混合使用。 通过需求选择starts例如选择Web。 我们就会发现pom.xml文件中就会自动配置了我们引入的starts。
!-- 摘取一部分 --
parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.0.0.RELEASE/versionrelativePath/ !-- lookup parent from repository --
/parentpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncodingproject.reporting.outputEncodingUTF-8/project.reporting.outputEncodingjava.version1.8/java.version
/properties
dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactIdoptionaltrue/optional/dependency
/dependencies添加controller层 新注解RestController ResponseBody与Controller的合体
//这个类的所有方法返回的数据直接写给浏览器如果是对象转为JSON
//ResponseBodyController
RestController
public class HelloWordController {RequestMapping(/hello)public String hello(){return hell;}
}优点 默认生成的SpringBoot项目我们只需要编写自己的逻辑。默认生成的Resources配置文件的目录结构 【1】static保存所有的静态资源。 [js/css/image] 【2】templates保存所有的模板页面[SpringBoot默认jar包使用嵌入式的 Tomcat默认不支持JSP页面]但可以使用模板引擎。freemarker、thymeleaf 【3】application.propertiesSpringBoot应用的配置文件。默认的配置都在此文件可以修改。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/83291.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!