每日学习:Spring——IOC使用注解实现依赖注入

    科技2026-02-19  6

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

    (1)对象比较多的话,开启注解扫描

    只有标记有注解的类,才会被创建对象且添加到ioc容器中

    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 http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 使用注解方式进行创建对象 1.开启注解扫描 含义:开启注解扫描,指定了 base-package 扫描指定的包,扫描包与子包中所有的类 查看类上是否有指定的注解, 如果类上有指定的注解,那么就创建给类对象, 放到spring容器中 --> <context:component-scan base-package="com.ly"/> </beans>

    (2)TestSpringIoc测试

    public class TestSpringIoc { private static final Logger log= LoggerFactory.getLogger(TestSpringIoc.class); private ClassPathXmlApplicationContext context; @Before public void init(){ //1:创建ioc 容器对象 暂时看成map context=new ClassPathXmlApplicationContext("applicationContext.xml"); //2:给定配置文件的名称 applicationContext.xml } @Test public void test01(){ //PersonService personService = new PersonService(); PersonService personService = (PersonService) context.getBean("personService"); log.debug(personService+"test01"); PersonDao personDao = (PersonDao) context.getBean("personDao"); log.debug(personDao+"test01"); } @Test public void test09(){ //PersonService personService = new PersonService(); PersonService personService = (PersonService) context.getBean("personService"); Person p = new Person(); p.setName("jack"); p.setPassword("12345"); boolean flag =personService.login(p); log.debug(flag+""); } }

    (3)PersonService

    Spring依赖注入-注解实现注入*** (1)注入是什么? 就是查找之后,进行赋值 (2)三种注入方式 : 》 1 @Autowired 或者 @Autowired @Qualifier(“bean的id”) 》 2 @Value("#{bean的id}") 》 3 @Resource(name=“bean的id值”)

    @Service public class PersonService { @Autowired// PersonDao personDao; public Boolean login(Person person2) { Person person = personDao.find(person2); if( person==null){ return false; }else{ return true; } } }

    (4) PersonDao

    @Repository public class PersonDao { public Person find(Person person2) { if("jack".equals(person2.getName())&& "12345".equals(person2.getPassword())){ return person2; }else{ return null; } } }

    运行结果:Test01;Test09

    Processed: 0.009, SQL: 9