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
= (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
;
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">
<context:component-scan base-package="com.wzx"/>
</beans>
(2)只有标记有注解的类,才会被创建对象且添加到ioc容器中(3)四个注解
@Controller("xxx")
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");
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 {
@Autowired
PersonDao personDao
;
}