1. Spring 5.X应用零配置开发
Spring 框架从5.x版本推荐使用注解形式来对java应用程序进行开发与配置,并且可以完全替代原始的XML+注解形式的开发,在使用注解形式进行项目开发与环境配置时,Spring框架提供了针对环境配置与业务bean开发相关注解。
注解 声明Bean注解 @Component: 组件没有明确规定其角色,作用在类级别上声明当前类为一个业务组件,被Spring Ioc容器维护 。 @Service: 在业务逻辑层(Service 层)类级别进行声明 。 @Repository: 在数据访问层(dao 层) 类级别声明 。 @Controller: 在展现层(MVC) 使用,标注当前类为一个控制器。 注入Bean注解 @AutoWired: Spring官方提供注解 。 @Inject: JSR-330提供注解(标准制定方) 。 @Resource: JSR-250提供注解。 注意:在Set方法或属性上声明,一般情况下通用一般开发中更习惯声明在属性上。 Spring5.x中配置与获取Bean注解 @Configuration: 作用与类上,将当前类声明为一个配置类,相当于一个xml配置文件。 @ComponentScan: 自动扫描指定包下标注有。 @Repository,@Service,@Controller @Component: 注解的类并由Ioc容器进行实例化和维护 。 @Bean: 作用于方法上,相当于xml 文件中声明当前方法返回值为一个bean 。 @Value: 获取properties文件指定key,value值。
-
IOC中Bean的实例化与获取
通过实例化AnnotationConfigApplicationContext类,接收配置参数类IocConfig,并获取UserService Bean实现方法调用。 1.在pom.xml中添加坐标相关配置
org.springframework spring-context5.2.4.RELEASE 2.创建Bean对象 UserDao.java和UserService.java 3.创建IocConfig配置类 //将当前类声明为一个配置类 @Configuration //设置扫描包范围 @ComponentScan("com.yjxxt.springboot") public class IocConfig { } 4.创建启动类执行测试 public class Starter { public static void main(String[] args) { //基于Java的配置类加载Spring的应用上下文 AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig.class); //获取指定的Bean对象 UserService userService = ac.getBean(UserService.class); //调用Bean对象的方法 userService.test(); } }org.apache.maven.plugins maven-compiler-plugin2.3.2 11 11 utf-8 -
@Bean注解使用
使用@Bean注解声明在方法(注意:方法名一般为bean对象名称)级别用于返回实例化的Bean对象。 1.创建Bean对象 AccountDao.java 2.修改IocConfig配置类 @Configuration @ComponentScan("com.yjxxt.springboot") public class IocConfig02 { //返回实例化的单例Bean对象 @Bean public AccountDao accountDao(){ return new AccountDao(); } } 3.创建启动类并执行测试 public class Starter02 { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig.class); //判断IocConfig对象是否是单例 System.out.println(ac.isSingleton("IocConfig")); //获取IocConfig对象 IocConfig iocConfig = ac.getBean(IocConfig.class); //获取AccountDao对象 AccountDao accountDao01 = iocConfig.accountDao(); AccountDao accountDao02 = iocConfig.accountDao(); System.out.println(accountDao01 + "," + accountDao02); accountDao01.test(); } } -
读取外部配置文件
通过@PropertySource注解声明到类级别来指定读取相关配置。 1.准备配置文件 user.properties # user.properties user.userName=admin user.password=admin jdbc.properties # jdbc.properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/hr? useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root 2.@PropertySource加载配置文件 properties配置文件 @Configuration @ComponentScan("com.yjxxt") @PropertySource(value = {"classpath:jdbc.properties","classpath:user.properties"}) public class IocConfig03 { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String password; // 控制台打印属性值信息 public void showConfigInfo(){ System.out.println("driver:" + driver + ",url:" + url); System.out.println("userName:" + userName + ",password:" + password); } } 3.其他Bean对象获取properties文件内容 @Service public class UserService { @Resource private UserDao userDao; @Value("${user.userName}") private String userName; @Value("${user.password}") private String password; public void test(){ System.out.println("UserService.test..."); userDao.test(); System.out.println("userName:" + userName + ",password:" + password); } } -
组合注解与元注解
Spring为了消除重复注解,在元注解上引入了组合注解,其实可以理解为对代码的重构,相当于注解的注解,拥有元注解的原始功能。 @Configuration注解就是组合注解,拥有@Component注解功能,即配置类本身也是一个被IOC维护的单例Bean。 1.自定义组合注解 组合注解MyCompScan定义 拥有元注解@Configuration + @ComponentScan(扫描器)两者功能 覆盖value属性 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Configuration @ComponentScan public @interface MyCompScan { //设置别名,当前属性为哪个注解服务 @AliasFor(annotation = ComponentScan.class , value = "value") String[] value() default {}; } 2.应用组合注解 @MyCompScan("com.yjxxt.springboot") @PropertySource(value = {"classpath:jdbc.properties","classpath:user.properties"}) public class IocConfig04 { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String password; public void showConfigInfo(){ System.out.println("driver:" + driver + ",url:" + url); System.out.println("userName:" + userName + ",password:" + password); } } 3.测试组合注解 public class Starter { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(IocConfig04.class); UserService userService = ac.getBean(UserService.class); userService.test(); } }
2. Spring MVC零配置创建与部署
1.pom.xml添加坐标相关配置org.springframework spring-web5.2.4.RELEASE org.springframework spring-webmvc5.2.4.RELEASE javax.servlet javax.servlet-api3.0.1 provided 2.添加源代码 @Controller public class HelloController { @RequestMapping("/index") public String index(){ return "index"; } } 3.添加视图(WEB-INF/views目录下创建index.jsp) Hello mvc! 4.SpringMVC配置类添加 @Configuration //在@Configuration注解的配置类中添加,用于为该应用添加SpringMVC的功能 @EnableWebMvc //扫描包范围 @ComponentScan("com.xxxx") public class MvcConfig { //配置JSP视图解析器 @Bean //将方法返回的结果交给IOC容器维护 public InternalResourceViewResolver viewResolver(){ //获取视图解析器 InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); //设置前缀 viewResolver.setPrefix("/WEB-INF/views/"); //设置后缀 viewResolver.setSuffix(".jsp"); //返回解析器对象 (交给IOC容器进行维护) return viewResolver; } } 5.入口文件代码添加 //实现WebApplicationinitializer 接口的类都可以在web应用程序启动时被加载 public class WebInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { //基于Java的配置类加载Spring的应用上下文 AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); //注册 Mvc 配置信息 ctx.register(MvcConfig.class); //设置 ServletContext 上下文信息 ctx.setServletContext(servletContext); //配置转发器 Dispatcher ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx)); //设置映射路径 servlet.addMapping("/"); //启动时即实例化 Bean servlet.setLoadOnStartup(1); } } 6.如果项目中存在静态资源文件,定义拦截器 //静态资源 handler不进行处理 直接响应到客户端 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } //配置拦截器 @Bean public LoginInterceptor loginInterceptor(){ return new LoginInterceptor(); } //添加拦截器到mvc 环境 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()); } springmvc org.apache.maven.plugins maven-compiler-plugin2.3.2 11 11 utf-8
3. Spring Boot
Spring-Boot正是为了解决繁琐的代码配置而产生的。Spring Boot 是一个在 Spring的基础上搭建的全新的框架,它的设计目的是用来简化Spring应用的初始搭建以及开发过程。
优点:简单、快速、方便。 特点: 1.可以使用SpringBoot创建独 Spring应用程序。 2.嵌入式Tomcat、Jetty容器、无需部署WAR包。 3.提供starter简化Maven。 4.自动配置Spring和第三方库。 5.提供生产就绪特征。 6.无代码生成和XML配置。 步骤: 1.配置依赖。 2.配置web.xml,加载Spring和Spring MVC。 3.配置数据库连接。 4.配置Spring事务。 5.配置加载配置文件的读取,开启注解。 6.配置日志文件。 7.配置完成后部署Tomcat服务器。
-
快速入门
pom.xml添加依赖坐标
org.springframework.boot spring-boot-starter-parent2.2.2.RELEASE org.springframework.boot spring-boot-starter-web 添加源代码 @Controller public class HelloController { @RequestMapping("hello") @ResponseBody public String hello(){ return "Hello SpringBoot"; } } 创建启动类 //SpringBoot 启动类 @SpringBootApplication public class Starter{ public static void main(String[] args) { SpringApplication.run(Starter.class, args); } } 注意:启动类在启动时会扫描注解(@Controller、@Service、@Repository、@Component),扫描位置为同包及其子包下的注解,所以启动类的位置应放置于根包目录下。 @SpringBootApplication组合注解 @SpringBootConfiguration: 包含@Configuration,用于定义一个配置类。 @EnableAutoConfiguration: SpringBoot会自动根据jar包的依赖来自动配置项目。 @ComponentScan: 告诉Spring哪个packages的注解标识的类会被Spring自动扫描并且装入bean容器。org.springframework.boot spring-boot-maven-plugin -
核心配置
1.Banner图标自定义 Spring Boot项目启动时默认加载 src/main/resources目录下的 banner.txt图标文件,如果该目录文件未提供,则使用Spring Boot默认。 http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something 2.Banner图标关闭 @SpringBootApplication public class StarterApplication { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(StarterApplication .class); //设置 banner 图标关闭 springApplication.setBannerMode(Banner.Mode.OFF); springApplication.run(); } } 3.配置文件 Spring Boot默认会读取全局配置文件,配置文件名固定为application.properties或application.yml, 放置在src/main/resource 资源目录下,使用配置文件来修改SpringBoot自动配置的默认值。 application.properties文件 ## 项目启动端口号配置 server.port=8989 ## 项目访问上下文路径 server.servlet.context-path=/mvc ## 数据源配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hr? useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root application.yml文件 ## 端口号 上下文路径 server: port: 8989 servlet: context-path: /mvc ## 数据源配置 spring: datasource: type: com.mchange.v2.c3p0.ComboPooledDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/hr username: root password: root 4.Starter坐标 Web starter 使用Spring MVC来构建RESTful Web应用,并使用Tomcat作为默认内嵌容器 Freemarker Starter & Thymeleaf starter 集成视图技术,引入Freemarker Starter , Thymeleaf Starterorg.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-freemarker JavaMail邮件发送Starterorg.springframework.boot spring-boot-starter-thymeleaf 引入AOP环境org.springframework.boot spring-boot-starter-mail 5.自动化配置 SpringBoot Starter坐标版本查看 以环境搭建spring-boot-starter-web坐标来简单分析SpringBoot自动化配置过程。org.springframework.boot spring-boot-starter-aoporg.springframework.boot spring-boot-starter-web Spring Boot自动化配置 Spring Boot的项目一般都会有*Application的入口类,入口类中提供main方法,这是一个标准的Java应用程序的入口方法。 Spring Boot通过maven中的starter导入了所需场景下的jar包,并通过主启动类上的@SpringBootApplication中的@EnableAutoConfiguration读取了 类路径下的META- INF/spring.factories下EnableAutoConfiguration的配置类,这些配置类使用@ConditionalOnClass来标注,根据@ConditionalOnClass标注的约束条件来引入自动化的环境配置。`org.springframework.boot spring-boot-starter-parent2.2.2.RELEASE -
Profile配置
Profile是Spring用来针对不同环境对不同配置提供支持的全局Profile配置使用application- {profile}.yml。 application-dev.yml开发环境配置文件 server: port: 8989 application-test.yml测试环境配置文件 server: port: 9999 application-prod.yml生产环境配置文件 server: port: 8686 application.yml 主配置文件 ## 环境选择配置 spring: profiles: active: dev -
日志配置
日志的输出对于系统bug定位无疑是一种比较有效的方式,也是项目后续进入生产环境后快速发现错误解决错误的一种有效手段。Spring Boot 默认使用LogBack日志系统,如果不需要更改为其他日志系统如Log4j2等,则无需多余的配置,LogBack默认将日志打印到控制台上。 如果要使用LogBack,原则上是需要添加dependency依赖的。
spring-boot-starter或者spring-boot-starter-web ,而这两个起步依赖中都已经包含了对于spring-boot-starter-logging的依赖。 1.项目中日志信息输出 Starter启动类中添加Log日志类,控制台打印日志信息。 @SpringBootApplication public class Starter { private static Logger logger = LoggerFactory.getLogger(Starter.class); public static void main(String[] args) { logger.info("SpringBoot 应用开始启动..."); SpringApplication.run(Starter.class); } } 2.日志输出格式配置 application.yml文件 logging: pattern: console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger- %msg%n" level: debug file: path: "." name: "springboot.log"org.springframework.boot spring-boot-starter-logging -
Freemarker视图集成
SpringBoot内部支持Freemarker视图技术的集成,并提供了自动化配置类FreeMarkerAutoConfiguration。 1.Starter坐标引入
2.添加Freemarker配置信息 Freemarker默认默认视图路径resources/templates目录(由自动化配置类FreemarkerProperties决定),该目录可以进行在application.yml中进行修改。 spring: freemarker: suffix: .ftl content-type: text/html #响应格式 charset: UTF-8 template-loader-path: classpath:/views/ 3.编写IndexController控制器转发视图 @Controller public class IndexController { @RequestMapping("index") public String index(){ return "index"; } } 4.views目录下添加index.ftl视图org.springframework.boot spring-boot-starter-freemarker -
Thymeleaf视图集成
SpringBoot支持多种视图技术集成,并且SpringBoot官网推荐使用Thymeleaf作为前端视图页面。 1.starter坐标引入
2.添加Thymeleaf配置信息 Thymeleaf默认默认视图路径resources/templates目录(由自动化配置类ThymeleafProperties 类决定),该目录可以进行在application.yml中进行修改。 ## 环境选择配置 spring: thymeleaf: prefix: classpath:/html/ ## 关闭 thymeleaf 页面缓存 cache: false 3.编写IndexController控制器转发视图 @Controller public class IndexController { @RequestMapping("index") public String index(Model model){ //设置请求域的值 model.addAttribute("msg","Hello SpringBoot"); return "index"; } } 4.html目录下添加index.html视图 修改Thymeleaf模板默认存放路径 (在resources目录下创建html文件夹)org.springframework.boot spring-boot-starter-thymeleaf -
SpringBoot静态资源访问
可以在resources资源目录下存放web应用静态资源文件。 默认静态资源路径 在resources目录下创建static或者public目录,存放images、js、css等静态资源文件。 自定义静态资源路径 在spring.resources.static-locations后面追加一个配置classpath:/os/ spring: # 修改默认的静态寻址资源目录 多个路径之间用逗号隔开 resources: static-locations: classpath:/public/,classpath:/static/,classpath:/os/



