本文主要是介绍SSM【篇四】之SpringDI,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Spring依赖注入-Xml方式 Dao
-(1)对象注入
实体类
public class A{private int id;private B b;
}
service类
public class XXXService{private int id;private XxxDao xxxdao;
}
举例
Test
@Testpublic 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.syy.service.PersonService"><property name="personDao" ref="personDao"/></bean><bean id="personDao" class="com.syy.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--使用注解方式进行创建对象1.开启注解扫描含义:开启注解扫描,指定了 base-package 扫描指定的包,扫描包与子包中所有的类查看类上是否有指定的注解, 如果类上有指定的注解,那么就创建给类对象,放到spring容器中--><context:component-scan base-package="com.syy"/></beans>
- (2)只有标记有注解的类,才会被创建对象且添加到ioc容器中
- (3)四个注解
@Component //其他层
@Repository //Dao层
@Service //Service层
@Controller("xxx")//Controller层
public class MyClass{
}
- (4)注解没有配置id,但是默认是 myClass
@Testpublic 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 或者 @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值")@AutowiredPersonDao personDao ;}
这篇关于SSM【篇四】之SpringDI的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!