1.导包
新建lib文件夹,如果存在就无需创建,导入之后一定要右键lib文件夹add as libray
2.在src文件夹下新建配置文件
右键new -选择XMLconfiguration file -spring config
配置文件主要负责创建对象跟注入属性
<?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>
3.创建bean包存放自定义对象
先用book类做一个测试,需要一个成员变量,封装一个set方法,一个show()方法
package com.bean;
public class Book
{
//创建私有成员变量
private String bName;
//获取set方法
public void setbName(String bName) {
this.bName = bName;
}
public void show(){
System.out.println("书名:"+this.bName);
}
}
4.在主配置文件创建对象
使用property标签传参数一定要在类里创建set方法,并且不能有带参的构造方法
不要在value中传递特殊符号,如果需要传递特殊符号通过VDATE方式,或者转义字符。
<?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是自己起的对象名
class是对象的全限定类名
全限定类型复制方法:
1.选中类
2.右键选择copy reference
-->
<bean id="firstBook" class="com.bean.Book" >
<!--
name是你成员变量的属性名
value是你传的参数
-->
<property name="bName" value="河南罗斯"></property>
</bean>
</beans>
5.测试类
package com.test; import com.bean.Book; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { //下载spring配置文件 ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); //通过getbean方法创建对象 Book firstBook = context.getBean("firstBook", Book.class); //调用已经创建好的show方法 firstBook.show(); } }