案例04 基于注解的依赖注入案例

基于注解的依赖注入方式实现学生信息新增。

1. 创建项目

Idea创建Java项目,项目名称为:case04-spring-student03。

2. 导入spring相关jar包

case04-spring-student03项目下创建lib目录,在lib目录下导入Jar包:

  • 核心包

spring-core-5.3.25.jar

spring-beans-5.3.25.jar

spring-context-5.3.25.jar

spring-expression-5.3.25.jar

  • AOP包

spring-aop-5.3.25.jar

  • 测试包

junit-4.6.jar

  • 依赖包

commons-logging-1.2.jar

3. 创建Spring配置文件

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启组件扫描-->
    <context:component-scan base-package="com.wfit"/>
</beans>

4. 创建StudentService接口

src目录下创建com.wfit.service包,此包目录下创建StudentService接口,声明addStudent方法。

public interface StudentService {
    //新增学生信息
    public void addStudent();
}

5.创建StudentServiceImpl实现类

src目录下创建com.wfit.service.impl包,此包目录下创建StudentServiceImpl实现类,实现addStudent方法。

@Service //标注业务逻辑组件
public class StudentServiceImpl implements StudentService {
    @Autowired  //@Autowired注解 完成自动配置
    private StudentDao studentDao;
    @Override
    public void addStudent() {
        //调用StudentDao中的saveStudent方法
        studentDao.saveStudent();
    }
}

6. 创建StudentDao类

com.wfit.dao目录下创建StudentDao.java类

@Repository //标注数据访问层
public class StudentDao {
    //保存学生信息
    public void saveStudent(){
        System.out.println("保存学生信息成功!");
    }
}

7. 创建测试类

src目录下创建com.wfit.test包,此包目录下创建TestStudent测试类。

public class TestStudent {
    @Test
    public void test(){
        //初始化Spring容器ApplicationContext,加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过容器获取StudentServiceImpl实例
        StudentService studentService =
                applicationContext.getBean("studentServiceImpl",StudentService.class);
        studentService.addStudent();
    }
}

8. 执行结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WFIT~SKY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值