spring入门(一) 根据xml实例化一个对象

文档: https://docs.spring.io/spring/docs/5.0.9.RELEASE/spring-framework-reference/core.html#beans-factory-metadata

包下载的位置  http://repo.spring.io/release/org/springframework/spring/5.0.9.RELEASE/

1.pom如下:

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>
    </dependencies>

2.建立User类

 1 public class User {
 2     private String name;
 3     private Integer age;
 4 
 5     public String getName() {
 6         return name;
 7     }
 8 
 9     public void setName(String name) {
10         this.name = name;
11     }
12 
13     public Integer getAge() {
14         return age;
15     }
16 
17     public void setAge(Integer age) {
18         this.age = age;
19     }
20 }
View Code

3.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans.xsd">
 6 
 7     <bean id="..." class="...">
 8         <!-- collaborators and configuration for this bean go here -->
 9     </bean>
10 
11     <bean id="..." class="...">
12         <!-- collaborators and configuration for this bean go here -->
13     </bean>
14 
15     <!-- more bean definitions go here -->
16 
17 </beans>

4.实例化User类

main方法里:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
1         //位置:setting/applicationContext.xml
2         ApplicationContext context = new ClassPathXmlApplicationContext("setting/applicationContext.xml");
3         User user = context.getBean("user",User.class);
4         System.out.println(user);

猜你喜欢

转载自www.cnblogs.com/ICE_Inspire/p/9721382.html