eclipse搭建springIOC

来源:互联网 发布:linux cd命令的用法 编辑:程序博客网 时间:2024/06/03 20:32

1、创建一个web项目

2、在src下面创建一个applicationContext.xml文件,该文件里面是spring的一些配置,文件头部是spring的dtd约束文件,版本根据导入的spring包来确定,本文先用现成的。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>

3、创建一个entity

package com.beijing.entity;


public class User {
int id;
String name;
String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

4、在applicationContext.xml文件中配置一个bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="user" class="com.beijing.entity.User">
        
    </bean>
</beans>

5、使用junit进行测试

package com.beijing.test;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.beijing.entity.User;


public class TestCase {
@Test
public void test1(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ac.getBean("user",User.class);
System.out.println(user);
}
}

这样我们获得了一个User对象。

整体目录结构,以及需要的jar包



当然我们也可以在applicationContext.xml文件中给bean进行初始化

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="user" class="com.beijing.entity.User">
        <property name="name" value="小明"></property>
    </bean>
</beans>

修改测试类为

package com.beijing.test;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.beijing.entity.User;


public class TestCase {
@Test
public void test1(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ac.getBean("user",User.class);      //这里实际是在说明配置文件中获取的bean是什么类型,或者说是强制转型
System.out.println(user);
System.out.println(user.getName());
}
}

输出结果为

 


好了,到这里spring的一个简单的IOC就这么实现了。

0 0
原创粉丝点击