Springboot(Xml 和 JavaConfig,Spring Boot 入门)


1.1 第一章 Xml 和 JavaConfig

Spring 使用 Xml 作为容器配置文件, 在 3.0 以后加入了 JavaConfig. 使用 java 类做配置文件使用。

1.1.1 什么是 JavaConfig

JavaConfig: 是 Spring 提供的使用 java 类配置容器。 配置 Spring IOC 容器的纯 Java 方法。
优点:
1.可以使用面像对象的方式, 一个配置类可以继承配置类,可以重写方法
2.避免繁琐的 xml 配置

1.1.2 Xml 配置容器

创建 001-pre-boot 项目
pom.xml

<dependencies>
	 <dependency>
		 <groupId>org.springframework</groupId>
		 <artifactId>spring-context</artifactId>
		 <version>5.3.1</version>
	 </dependency>
	 <dependency>
		 <groupId>junit</groupId>
		 <artifactId>junit</artifactId>
		 <version>4.12</version>
	 </dependency>
</dependencies>
<build>
	 <plugins>
		 <!-- 编译插件 -->
		 <plugin>
			 <artifactId>maven-compiler-plugin</artifactId>
			 <!-- 插件的版本 -->
			 <version>3.5.1</version>
			 <!-- 编译级别 -->
			 <configuration>
				 <source>1.8</source>
				 <target>1.8</target>
				 <!-- 编码格式 -->
				 <encoding>UTF-8</encoding>
			 </configuration>
	 </plugin>
	 </plugins>
</build>

创建数据类 Student

package com.bjpowernode.vo
public class Student {
	 private Integer id;
	 private String name;
	 private Integer age;
	 // set | get 
}

resources 目录下创建 Spring 的配置文件 applicationContext.xml


<bean id="myStudent" class="com.bjpowernode.vo.Student">
 <property name="id" value="1001" />
 <property name="name" value="李强国" />
 <property name="age" value="20" />
</bean>

单元测试:

@Test
public void test01(){
 String config="applicationContext.xml";
 ApplicationContext ctx = new 
ClassPathXmlApplicationContext(config);
 Student student = (Student) ctx.getBean("myStudent");
 System.out.println("student="+student);
}

1.1.3 JavaConfig 配置容器

JavaConfig 主要使用的注解
@Configuration:放在类的上面, 这个类相当于 xml 配置文件,可以在其中声明 bean
@Bean:放在方法的上面, 方法的返回值是对象类型, 这个对象注入到 spring ioc 容器

创建配置类(等同于 xml 配置文件)

package com.bjpowernode.config;
import com.bjpowernode.vo.Persion;
import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.util.Date;
/**
* @Configuration:表示当前类是 xml 配置文件的作用 
 * 在这个类中有很多方法, 方法的返回值是对象。
* 在这个方法的上面加入@Bean, 表示方法返回值的对象放入到容器中。
* @Bean == <bean></bean>
*/
@Configuration
public class SpringConfig {
	 /**
	 * 定义方法, 方法的返回值是对象。
	 * @Bean:表示把对象注入到容器中。 
	 * 位置: 方法的上面
	 * @Bean 没有使用属性,默认对象名称是方法名 
	 */
	 @Bean
	 public Student createStudent(){
		 Student student = new Student();
		 student.setId(1002);
		 student.setName("周仓");
		 student.setAge(29);
		 return student;
	 }
	 // name :指定对象的名称
	 @Bean(name = "myStudent2")
	 public Student makeStudent(){
		 Student student = new Student();
		 student.setId(1003);
		 student.setName("诸葛亮");
		 student.setAge(30);
		 return student;
	 }
	 @Bean
	 public Date myDate(){
		 return new Date();
	 }
	}
}

测试方法:

//使用 JavaConfig
@Test
public void test02(){
	 //没有 xml 配置文件,使用 java 类代替 xml 配置文件 的作用
	 ApplicationContext ctx = new 
	AnnotationConfigApplicationContext(SpringConfig.class);
	 Student student = (Student) ctx.getBean("createStudent");
	 System.out.println("student==="+student);
}
@Test
public void test03(){
	 //没有 xml 配置文件,使用 java 类代替 xml 配置文件 的作用
	 ApplicationContext ctx = new 
	AnnotationConfigApplicationContext(SpringConfig.class);
	 Student student = (Student) ctx.getBean("myStudent2");
	 System.out.println("myStudent2==="+student);
	 Object myDate = ctx.getBean("myDate");
	 System.out.println("myDate = " + myDate);
}

1.1.4 @ImportResource

@ImportResource 是导入 xml 配置,等同于 xml 文件的 resources
创建数据类:

public class Cat {
	 private String cardId;
	 private String name;
	 private Integer age;
	 // set |get 
}

创建配置文件 beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean id="myCat" class="com.bjpowernode.vo.Cat">
	 <property name="cardId" value="XSET29001" />
	 <property name="name" value="tom 猫"/>
	 <property name="age" value="3" />
 </bean>
</beans>

创建配置类:

@Configuration
@ImportResource(value = 
{"classpath:beans.xml","classpath:applicationContext.xml"})
public class SystemConfig {
 //使用@Bean 声明 bean
}

创建测试方法:

@Test
public void test04(){
	 //没有 xml 配置文件,使用 java 类代替 xml 配置文件 的作用
	 ApplicationContext ctx = 
	new AnnotationConfigApplicationContext(SystemConfig.class);
	 Cat cat = (Cat) ctx.getBean("myCat");
	 System.out.println("cat==="+cat);
}

1.1.5 @PropertyResource

@PropertyResource 是读取 properties 属性配置文件

在 resources 目录下创建 config.properties

tiger.name=东北老虎
tiger.age=6

创建数据类 Tiger

@Component("tiger")
public class Tiger {
	 @Value("${tiger.name}")
	 private String name;
	 @Value("${tiger.age}")
	 private Integer age;
	 @Override
	 public String toString() {
		 return "Tiger{" +
		 "name='" + name + '\'' +
		 ", age=" + age +
		 '}';
	 }
}

修改 SystemConfig 文件

@Configuration
@PropertySource(value = "classpath:config.properties")
@ComponentScan(value = "com.bjpowernode.vo")
public class SystemConfig {
 //使用@Bean 声明 bean
}

创建测试方法

@Test
public void test05(){
	 //没有 xml 配置文件,使用 java 类代替 xml 配置文件 的作用
	 ApplicationContext ctx = 
	new AnnotationConfigApplicationContext(SystemConfig.class);
	 Tiger tiger = (Tiger) ctx.getBean("tiger");
	 System.out.println("Tiger==="+tiger);
}

1.2 第二章 Spring Boot 入门

1.2.1 第一种方式:https://start.spring.io

使用 spring boot 提供的初始化器。 向导的方式,完成 spring boot 项目的创建: 使用方便。

1.2.1.1 创建项目步骤

step 1: 新建项目
在这里插入图片描述

step 2
在这里插入图片描述

step 3 选择依赖
在这里插入图片描述

step 4 : 最后创建项目,设置项目的目录位置
step 5: Spring Boot 项目目录结构
在这里插入图片描述

1.2.1.2 起步依赖

在这里插入图片描述

1.2.2 第二种方式,使用 springboot 提供的初始化器, 使用的国内的地址

国内地址: https://start.springboot.io
创建项目的步骤同上
在这里插入图片描述

1.2.3 第三种方式 使用 maven 向导创建项目

创建一个普通 maven 项目
在这里插入图片描述

添加 gav
在这里插入图片描述

点击 finish 创建,完成项目创建。
修改项目的目录
在这里插入图片描述

添加 Spring Boot 依赖

<dependencies>
	 <dependency>
		 <groupId>org.springframework.boot</groupId>
		 <artifactId>spring-boot-starter-web</artifactId>
	 </dependency>
	 <dependency>
		 <groupId>org.springframework.boot</groupId>
		 <artifactId>spring-boot-starter-test</artifactId>
		 <scope>test</scope>
	 </dependency>
</dependencies>
<build>
	 <plugins>
		 <plugin>
			 <groupId>org.springframework.boot</groupId>
			 <artifactId>spring-boot-maven-plugin</artifactId>
			 </plugin>
	 </plugins>
</build>

创建启动类:加入@SpringBootApplication 注解

package com.bjpowernode;
@SpringBootApplication
public class MySpringBootMain {
 public static void main(String[] args) {
 SpringApplication.run(MySpringBootMain.class,args);
 }
}

1.2.3.1 入门案例

1.2.3.2 入门案例分析

1.2.3.3 重要注解

@SpringBootApplication : @SpringBootApplication 是 一 个 复 合 注 解 , 是 由@SpringBootConfiguration, @EnableAutoConfiguration ,@ComponentScan 联合在一起组成的。

@SpringBootConfiguration : 就 是 @Configuration 这 个 注 解 的 功 能 , 使 用@SpringBootConfiguration 这个注解的类就是配置文件的作用。
@EnableAutoConfiguration:开启自动配置, 把一些对象加入到 spring 容器中。

@ComponentScan:组件扫描器, 扫描注解,根据注解的功能,创建 java bean,给属性赋值等。组件扫描器默认扫描的是 @ComponentScan 注解所在的类, 类所在的包和子包。

1.2.4 Spring Boot 核心配置文件

Spring Boot 的核心配置文件用于配置 Spring Boot 程序,名字必须以 application 开始

1.2.4.1 .properties 文件(默认采用该文件)

在 002-springboot-springmvc 项目基础上,进行修改
项目名称:003-springboot-port-context-path

通过修改 application.properties 配置文件,在修改默认 tomcat 端口号及项目上下文件根键值对的 properties 属性文件配置方式

#设置访问端口号
server.port=9092
#应用的 contextpath
server.servlet.context-path=/boot

启动应用, 在浏览器访问 http://localhost:9092/boot/

1.2.4.2 .yml 文件

项目名称:005-springboot-yml,在之前项目基础之上

yml 是一种 yaml 格式的配置文件,主要采用一定的空格、换行等格式排版进行配置。

yaml 是一种直观的能够被计算机识别的的数据序列化格式,容易被人类阅读,yaml 类似于 xml,但是语法比 xml 简洁很多,值与前面的冒号配置项必须要有一个空格, yml 缀也可以使用 yaml 后缀

server:
 port: 9091
 servlet:
 context-path: /boot

注意 : 当两种格式配置文件同时存在 ,在 SpringBoot2.4 开始, 使用的是 yml 配置文件.

修改配置名称都为 application。

重新运行 Application ,查看启动的端口及上下文根

推荐使用 yml 格式配置文件

1.2.4.3 多环境配置

在实际开发的过程中,我们的项目会经历很多的阶段(开发->测试->上线),每个阶段的配置也会不同,例如:端口、上下文根、数据库等,那么这个时候为了方便在不同的环境之间切换,SpringBoot 提供了多环境配置,具体步骤如下

项目名称:006-springboot-multi-environment为每个环境创建一个配置文件,命名必须以 application-环境标识.properties|yml
在这里插入图片描述
application.properties

#指定使用的环境文件
#spring.profiles.active=dev
spring.profiles.active=test

application-dev.properties

#开发环境的信息
server.port=9091
server.servlet.context-path=/mydev

application-product.properties

server.port=9093
server.servlet.context-path=/myprod

application-test.properties

#开发环境的信息
server.port=9091
server.servlet.context-path=/mydev

1.2.4.4 Spring Boot 自定义配置

SpringBoot 的核心配置文件中,除了使用内置的配置项之外,我们还可以在自定义配置,然后采用如下注解去读取配置的属性值

1.2.4.4.1 @Value 注解

@Value(“${key}”) , key 来自 application.properties(yml)

application.properties:添加两个自定义配置项 school.name 和
school.website。在 IDEA 中可以看到这两个属性不能被 SpringBoot 识别,背景是桔色的

server.port=9090
server.servlet.context-path=/myboot
school.name=动力节点
school.address=北京大兴区
school.website=www.bjpowernode.com
site=www.bjpowernode.com

读取配置文件数据

@Controller
public class HelloController {
	 @Value("${server.port}")
	 private String port;
	 @Value("${school.name}")
	 private String name;
	 @Value("${site}")
	 private String site;
	 
	 @RequestMapping("/hello")
	 @ResponseBody
	 public String doHello(){
		 return "hello, port:" + port + "学校:"+name+",网站:"+site;
	 }
}

启动应用 Application , 访问浏览器

1.2.4.4.2 @ConfigurationProperties

项目名称:008-springboot-custom-configuration
将整个文件映射成一个对象,用于自定义配置项比较多的情况

案例演示
在 com.bjpowernode.springboot.config 包下创建 SchoolInfo 类,并为该 类加上Component 和 ConfigurationProperties 注解,prefix 可以不指定,如果不指定,那么会去配置文件中寻找与该类的属性名一致的配置,prefix 的作用可以区分同名配置

@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
	 private String name;
	 private String address;
	 private String website;
	 // set | get 方法
}

创建 SchoolController

@Controller
public class SchoolController {
	 @Resource
	 private SchoolInfo schoolInfo;
	 
	 @RequestMapping("/myschool")
	 @ResponseBody
	 public String doSchool(){
		 return "学校信息:"+schoolInfo.toString();
	 }
}

执行 Application , 访问浏览器查看数据

1.2.4.4.3 警告解决

➢ 在 SchoolInfo 类中使用了 ConfigurationProperties 注解,IDEA 会出现一个警告,不影响程序的执行
在这里插入图片描述

➢ 点击 open documentnation 跳转到网页,在网页中提示需要加一个依赖,我们将这个依赖拷贝,粘贴到 pom.xml 文件中
在这里插入图片描述

<!--解决使用@ConfigurationProperties 注解出现警告问题-->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-configuration-processor</artifactId>
 <optional>true</optional>
</dependency>
1.2.4.4.4 中文乱码

如果在 SpringBoot 核心配置文件中有中文信息,会出现乱码:
◼ 一般在配置文件中,不建议出现中文(注释除外)
◼ 如果有,可以先转化为 ASCII 码
在这里插入图片描述

1.2.4.4.5 提示

大家如果是从其它地方拷贝的配置文件,一定要将里面的空格删干净

1.2.5 Spring Boot 中使用 JSP

1.2.5.1 在 pom.xml 文件中配置以下依赖项

<!--引入 Spring Boot 内嵌的 Tomcat 对 JSP 的解析包,不加解析不
了 jsp 页面-->
<!--如果只是使用 JSP 页面,可以只添加该依赖-->
<dependency>
	 <groupId>org.apache.tomcat.embed</groupId>
	 <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--如果要使用 servlet 必须添加该以下两个依赖-->
<!-- servlet 依赖的 jar 包-->
<dependency>
	 <groupId>javax.servlet</groupId>
	 <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- jsp 依赖 jar 包-->
<dependency>
	 <groupId>javax.servlet.jsp</groupId>
	 <artifactId>javax.servlet.jsp-api</artifactId>
	 <version>2.3.1</version>
</dependency>
<!--如果使用 JSTL 必须添加该依赖-->
<!--jstl 标签依赖的 jar 包 start-->
<dependency>
	 <groupId>javax.servlet</groupId>
	 <artifactId>jstl</artifactId>
</dependency>

1.2.5.2 在 pom.xml 的 build 标签中要配置以下信息

SpringBoot 要求 jsp 文件必须编译到指定的 META-INF/resources 目录下才能访问,否则访问不到。其实官方已经更建议使用模板技术(后面会讲模板技术)

<!—
 SpringBoot 要求 jsp 文件必须编译到指定的
META-INF/resources 目录下才能访问,否则访问不到。
 其它官方已经建议使用模版技术(后面会课程会单独讲解模版技
术)
-->
<resources>
	 <resource>
		 <!--源文件位置-->
		 <directory>src/main/webapp</directory>
		 <!--指定编译到META-INF/resource,该目录不能随便写-->
		 <targetPath>META-INF/resources</targetPath>
		 <!--指定要把哪些文件编译进去,**表示 webapp 目录及子
		目录,*.*表示所有文件-->
		 <includes>
			 <include>**/*.*</include>
		 </includes>
	 </resource>
</resources>

1.2.5.3 在 application.properties 文件配置 Spring MVC 的视图展示为jsp,这里相当于 Spring MVC 的配置

#配置 SpringMVC 的视图解析器
#其中:/相当于 src/main/webapp 目录
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

集成完毕之后,剩下的步骤和我们使用 Spring MVC 一样

1.2.5.4 在 com.bjpowernode.springboot.controller 包 下 创 建JspController 类,并编写代码

@Controller
public class SpringBootController {
	 @RequestMapping(value = "/springBoot/jsp")
	 public String jsp(Model model) {
		 model.addAttribute("data","SpringBoot 前端使用 JSP	页面!");
		 return "index";
	 }
}

1.2.5.5 在 src/main 下创建一个 webapp 目录,然后在该目录下新建index.jsp 页面

如果在webapp目录下右键,没有创建jsp的选项,可以在Project Structure中指定webapp为 Web Resource Directory
在这里插入图片描述

1.2.5.6 在 jsp 中获取 Controller 传递过来的数据

在这里插入图片描述

1.2.5.7 重新运行 Application,通过浏览器访问测试

在这里插入图片描述

1.2.6 Spring Boot 中使用 ApplicationContext

在 main 方法中 SpringApplication.run()方法获取返回的 Spring 容器对象,再获取业务 bean进行调用.

创建 Spring Boot 项目:010-springboot-container
指定项目的 gav 和版本等信息

在这里插入图片描述

选择依赖:
在这里插入图片描述

创建一个接口 UserService 和他的实现类

创建启动类, main 方法中获取容器对象

1.2.7 CommandLineRunner 接口

开发中可能会有这样的情景。需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot 给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为 CommandLineRunner 和 ApplicationRunner。他们的执行时机为容器启动完成的时候。这两个接口中有一个 run 方法,我们只需要实现这个方法即可。这两个接口的不同之处
在于: ApplicationRunner 中 run 方 法 的 参 数 为 ApplicationArguments , 而CommandLineRunner接口中 run 方法的参数为 String 数组

创建 Spring Boot 项目,不用选依赖,或者修改 010-springboot-container
在这里插入图片描述

创建 SomeService 接口和实现类,定义 sayHello()方法

public interface SomeService {
	 void sayHello(String name);
}
@Service("someService")
public class SomeServiceImpl implements SomeService {
	 @Override
	 public void sayHello(String name) {
		 System.out.println("欢迎:"+name);
	 }
}

实现 CommandLineRunner 接口

@SpringBootApplication
public class Application implements CommandLineRunner {
	 public static void main(String[] args) {
		 //run 方法返回值是容器对象
		 //1.创建容器对象
		 ConfigurableApplicationContext ctx = 
		SpringApplication.run(Application.class, args);
		 SomeService service = (SomeService) ctx.getBean("someService");
		 service.sayHello("李四");
	 }
	 @Override
	 public void run(String... args) throws Exception {
		 //2. 容器对象创建好,执行 run
		 System.out.println("输出, 在容器对象创建好后执行的代码");
	 }
}

运行主类,查看输出结果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值