一、前提知识
- 学习本门课程,需要熟悉Spring的使用(基于配置文件的方式)
二、基础环境搭建
1. 开发工具
- Maven3 – Maven的安装 使用 等等连接
- JDK1.8 – JDK安装连接
- IntelliJ IDEA 2019.1.3 x64 IDEA的链接使用等等
- Lombok – lombok的安装使用链接
2. 框架体系
- Spring 4
3. 环境搭建
(1)新建Maven工程
(2)pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.trnt</groupId>
<artifactId>spring.annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
(3)测试
- 实体类Person
在/src/main/java/bean/下创建实体Person
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Lombok
* @Data 注解在属性上,为单个属性提供set/get方法 ;
* 注解在类上,为该类所有属性都提供set/get方法,都提供默认构造方法
* @NoArgsConstructor 提供无参构造-Spring利用反射创建bean,需要无参构造
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
}
- bean的配置文件
在/src/main/resources/下创建 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="person" class="bean.Person">
<property name="name" value="jerry"></property>
<property name="age" value="18"></property>
</bean>
</beans>
- 测试类MainTest
在/src/test/下创建测试类MainTest
import bean.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest {
//创建bean:基于Spring配置文件
@Test
public void test01() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
}
- 运行结果
Person(name=jerry, age=18)