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

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

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

在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 {
    
    
}

运行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37924905/article/details/108965053