在建立好一个基本的maven project 之后,导入基本的spring jar包,下面就可以进行基本的使用了。
1.首先,和平时一样定义一个类
例如:
/**
* 定义一个类
* @author Administrator
*
*/
public class Person {
public String name = "";
public String getName() {
return name;
}
//public void setName(String name) {
// this.name = name;
//}
}
2.在src/main/resource 下建立Beans.xml 文件
<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="person"
class="com.shinion.basic.helloworld.Person">
</bean>
</beans>
文件内容中,重要的是bean标记里面,id代表名字,也可以起其他自定义的名字,比如"aaa"都可以
3.调用:
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Person person =null;
person = (Person)context.getBean("person");
if(person!= null) {
person.name = "aaa";
System.out.println(person.getName());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
在需要使用的方法中,开始调用,我这里用的是一个测试类的主函数,调用步骤主要是两步,第一,定义context,第二,contex.getbean()方法。获得对象后,即和平时一样使用