概念:Spring 是一个轻量级(低耦合)的开源框架,用于管理bean和维护bean与bean之间的关系
1. 新建java项目spring_1
2. 新建lib文件夹导入jar包,并add build path
commons-collections-3.2.jar
commons-logging.jar
spring-aop-4.0.6.RELEASE.jar
spring-beans-4.0.6.RELEASE.jar
spring-context-4.0.6.RELEASE.jar
spring-core-4.0.6.RELEASE.jar
spring-expression-4.0.6.RELEASE.jar
3. 新建HelloWorld类
1 package com.yf.hello; 2 3 public class HelloWorld { 4 5 private String name ; 6 7 public String getName() { 8 return name; 9 } 10 11 public void setName(String name) { 12 System.out.println("setName="+name); 13 this.name = name; 14 } 15 16 public HelloWorld(){ 17 System.out.println("constructor1.."+name); 18 } 19 20 21 public HelloWorld(String name) { 22 this.name = name; 23 System.out.println("constructor2.."+name); 24 } 25 26 @Override 27 public String toString() { 28 return "HelloWorld [name=" + name + "]"; 29 } 30 }
4. 新建spring的配置文件 applicationContext.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="helloWorld" class="com.yf.hello.HelloWorld" > 8 <property name="name"><value>zhangsan</value></property> 9 <!-- <constructor-arg type="String" value="李四"></constructor-arg> --> 10 </bean> 11 </beans>
5. 新建测试类:
1 package com.yf.hello; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Main { 7 8 public static void main(String[] args) { 9 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); 10 HelloWorld helloWorld = (HelloWorld) ac.getBean("helloWorld"); 11 System.out.println(helloWorld); 12 } 13 14 }
注: 使用属性注入bean时,需要确保该类有默认的构造方法(通过反射方式)