Spring学习_第一个Spring项目

下载Spring框架spring-framework-4.3.10.RELEASE-dist.zip:
http://maven.springframework.org/release/org/springframework/spring/4.3.10.RELEASE/
在这里插入图片描述
初期学习需要使用其中五个jar:
spring-beans-4.3.10.RELEASE.jar
spring-aop-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar

外加一个三方日志jar:
commons-logging-1.1.1.jarhttps://mvnrepository.com/artifact/commons-logging/commons-logging/1.1.1

1、搭建配置环境

将这六个jar构建到项目中。
当然,如果你使用的工具是IDEA的话,上面的步骤统统不用做(哈哈哈哈哈)

2、编写配置文件

src下新建文件:applicationContext.xml

<?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="UserDao" class="com.itheima.ioc.UserDaoImpl"/>
    <bean id="person" class="com.itheima.entity.Person">
        <property name="id" value="1"></property>
        <property name="name" value="zs"></property>
        <property name="age" value="13"></property>
        <property name="sex" value="true"></property>
    </bean>
</beans>

3、开发Spring程序

建包:com.itheima.ioc
包下建接口:UserDao

package com.itheima.ioc;
public interface UserDao {
    
    
    public void say();
}

实现接口:UserDaoImpl

package com.itheima.ioc;
public class UserDaoImpl implements UserDao{
    
    
    @Override
    public void say() {
    
    
        System.out.println("UserDao say hello world!");
    }
}

测试类:TestIoc

package com.itheima.ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
    
    
    public static void main(String[] args) {
    
    
        //初始化spring容器,加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过容器获取userDao实例
        UserDao userDao = (UserDao) applicationContext.getBean("UserDao");
        //调用say方法
        userDao.say();
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person.toString());
    }
}

愿你心如花木,向阳而生

猜你喜欢

转载自blog.csdn.net/nbcsdn/article/details/98871411