Spring环境搭建

1. 使用Maven工具构建Java Project,修改pom.xml

<properties>
    
    <java.version>1.8java.version>
    
    <spring.version>4.1.6.RELEASEspring.version>
properties>
<dependencies>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>${spring.version}version>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-beansartifactId>
        <version>${spring.version}version>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>${spring.version}version>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-context-supportartifactId>
        <version>${spring.version}version>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-expressionartifactId>
        <version>${spring.version}version>
    dependency>
dependencies>

2.  在src/main/resources下创建applicationContext.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"> 

beans>

applicationContext.xml是spring容器的配置文件,spring的功能基本都在这个文件配置,文件名并不是固定,并没有默认的位置,需要明确指定加载的路径。

3. 测试

(1) 创建实体类Person

public class Person {
    
    private Integer userId;
    private String userName;
    private Integer age;
    
    public Person() {
        
    }
    public Person(Integer userId, String userName, Integer age) {
        this.userId = userId;
        this.userName = userName;
        this.age = age;
    }
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

(2) 在applicationContext.xml中配置


<bean id="peo" class="com.linhw.demo.spring.Person"/>

(3) spring 容器初始化,spring bean实例化

public class SpringTest {
    
    public static void main(String[] args) {
        //加载配置文件,spring 容器初始化
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        //spring bean 实例化
        Person person = ctx.getBean("peo",Person.class);
        System.out.println(person);
    }

}

你可能感兴趣的:(Spring环境搭建)