Spring入门:第一个Spring程序

本文详细介绍了如何在IDEA中配置Spring运行环境,包括导入必要的库,创建Service接口与实现类,以及在beans.xml中配置Bean。通过一个具体的UserService示例,展示了如何进行依赖注入,并在Lesson测试类中成功调用方法,验证了配置的正确性。
摘要由CSDN通过智能技术生成

在idea的运行环境下,配置好Spring运行环境(通俗的理解配置环境就是在工程文件里面导入需要的jar包
这里附上导入成功后的目录(网络上有很多很详细的导入过程,这里不在赘述)
在这里插入图片描述
1、创建Service接口和Service实现类

public interface UserService {
    void add();
    void add(User user); //方法的重载
}
public class UserServiceImpl implements UserService
    
    
	private String  name;
    

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void add(User user) {
        System.out.println("添加用户"+user);
    }

    public UserServiceImpl(){
        System.out.println("UserServiceImpl()调用了");
    }

    @Override
    public void add() {
        System.out.println("创建用户。。。。" + name);
    }
}

2、在beans.xml文件里面配置beans

<?xml version="1.0" encoding="utf-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">


    <!--配置一个bean-->
    <!--spring内部创建对象的原理
    1.解析xml文件,获取类名,id,属性
    2.通过反射,用类型创建对象
    3.给创建对象赋值
    -->
    <bean id = "userService" class = "com.service.UserServiceImpl">
    <!--依赖注入数据,调用属性set方法 -->
        <property name="name" value="zhangsan">  </property>

    </bean>
</beans>

3、最后创建Lesson测试

public class Lesson {

    @Test
    public void test(){

		//加载beans.xml这个spring配置文件,内部就会创建对象,ClassPath类路径加载:指的就是classes路径
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //从spring容器获取userService对象
        UserService  userService = (UserService) context.getBean("userService");
        userService.add();
    }
}

4、测试通过
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值