Spring——IOC使用注解实现依赖注入

本文详细介绍了如何在Spring Boot应用中使用@Autowired注解注入依赖,并展示了如何在配置文件中开启组件扫描。通过PersonService、PersonDao和测试类实例,展示了从启用注解到实际运行的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思维导图:
在这里插入图片描述

这边我用一个案例来说明。

在personService中用注解@Autowired注入personDao这个类

开启注解(也叫扫包)

要使用注解,首先要在配置文件中开启注解:

//这里我是扫描我自己com.lbl的包
<context:component-scan base-package="com.lbl"></context:component-scan>

代码:

PersonServiceTest

package com.lbl.service;

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

public class PersonServiceTest {
    ClassPathXmlApplicationContext onctext=new
            ClassPathXmlApplicationContext("applicationContext.xml");
    @Test
    public void test01(){
        //这里用类名的小写获取
        Object personService = onctext.getBean("personService");
        System.out.println(personService);
    }

}

PersonService

package com.lbl.service;

import com.lbl.dao.PersonDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonService {
    @Autowired
    PersonDao personDao;
}

PersonDao

package com.lbl.dao;

import org.springframework.stereotype.Repository;

@Repository
public class PersonDao {
}

运行结果:

在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值