Day21SSM之SpringDI

    科技2025-10-17  11

    Spring依赖注入-Xml方式 Dao

    -(1)对象注入

    public class A{ private int id; private B b; } public class XXXService{ private int id; private XxxDao xxxdao; }

    Test

    @Test public void test09(){ //PersonService personService = new PersonService(); PersonService personService = (PersonService) context.getBean("personService"); Person p = new Person(); p.setUsername("jack"); p.setPassword("12345"); boolean flag =personService.login(p); log.debug(flag+""); }

    PersonService

    public class PersonService { private static final Logger log= LoggerFactory.getLogger(PersonService.class); //private PersonDao personDao = new PersonDao(); private PersonDao personDao ; public void setPersonDao(PersonDao personDao) { this.personDao = personDao; } public boolean login(Person p) { log.debug(p+" login"); Person person = personDao.find(p); if(person==null) { return false; }else{ return true; } } }

    PersonDao

    public class PersonDao { public Person find(Person p) { if("jack".equals(p.getUsername())&&"12345".equals(p.getPassword())){ return p; }else{ return null; } } }

    applicationContext.xml

    <bean id="personService" class="com.wzx.service.PersonService"> <property name="personDao" ref="personDao"/> </bean> <bean id="personDao" class="com.wzx.dao.PersonDao"> </bean>

    Spring依赖注入-注解创建对象***

    (1)对象比较多的话,开启注解扫描 <?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.wzx"/> </beans> (2)只有标记有注解的类,才会被创建对象且添加到ioc容器中(3)四个注解 //@Component //其他层 //@Repository //Dao层 //@Service //Service层 @Controller("xxx")//Controller层 public class MyClass{ } 注解没有配置id,但是默认是 myClass @Test public void test10(){ PersonService personService = (PersonService) context.getBean("personService"); log.debug(personService+" test10"); PersonDao personDao = (PersonDao) context.getBean("personDao");//id为类名首字符小写 log.debug(personDao +" test10"); }

    Spring依赖注入-注解实现注入***

    (1)注入是什么? 就是查找之后,进行赋值(2)三种注入方式 》1 *** @Autowired 或者 @Autowired @Qualifier(“bean的id”) 》2 @Value("#{bean的id}") 》3 @Resource(name=“bean的id值”) @Service public class PersonService { //private PersonDao personDao = new PersonDao(); //第一种:@Autowired或者 @Autowired和@Qualifier("bean的id")搭配 //第二种:@Value("#{bean的id}") //第三种:@Resource(name="bean的id值") @Autowired PersonDao personDao ; }
    Processed: 0.010, SQL: 8