如何利用spring操纵一个对象呢。这是spring的最简单的一个作用。
我感觉一共有3步骤”
第一:写一个spring的xml。
第二:实例化spring容器。
第三:从xml里面获得具体的bean(也就是实际要操纵的对象)
首先引入jar就不说了。
接着写一个spring.XML
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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">
<beanid="fish"class="com.fish.Person"></bean>
</beans>
其实spring一个bean就对应着一个对象。Id要保证在spring是唯一的。Calss是对应的要操作的类。要加包名的。这个xml放在src目录下。
这个要操作的类person。
Person.JAVA
packagecom.fish;
public
class Person {
Stringname ;
Stringid;
publicString getName() {
return
name;
}
public
void setName(String name) {
this.name = name;
}
publicString getId() {
return
id;
}
public
void setId(String id) {
this.id = id;
}
}
那如何操纵person这个类呢?
下面写一个测试方法:
package com.fish;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContextcontext=new ClassPathXmlApplicationContext("spring.xml");//这是一个实例化spring容器的方法。Spring是你写的xml。其实在实例化容器的是时候你bean中的类就被实例化了。
Person p=(Person)context.getBean("fish");//通过获得bean的id这是你就拥有person对象了
p.setName("aa");那么这个对象自然就有他自身的一些属性和方法。
p.setId("12");
System.out.println(p.getName()+p.getId());
}
}