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">
<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(){
context
=new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test01(){
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
= (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