From:一条被猫抛弃的他乡流浪狗!

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如下:

 1 <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
 2         <dependency>
 3             <groupId>org.springframework</groupId>
 4             <artifactId>spring-core</artifactId>
 5             <version>5.0.9.RELEASE</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>org.springframework</groupId>
 9             <artifactId>spring-context</artifactId>
10             <version>5.0.9.RELEASE</version>
11         </dependency>
12         <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
13         <dependency>
14             <groupId>org.springframework</groupId>
15             <artifactId>spring-beans</artifactId>
16             <version>5.0.9.RELEASE</version>
17         </dependency>
18         <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
19         <dependency>
20             <groupId>org.springframework</groupId>
21             <artifactId>spring-expression</artifactId>
22             <version>5.0.9.RELEASE</version>
23         </dependency>
View Code

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);

 

posted @ 2018-09-28 22:50  ICE_Inspire  阅读(358)  评论(0编辑  收藏  举报