SpringIOC
什么是IOC?
- 把原来new对象的这种方式转换成了,spring通过反射创建对象的方式
- spring创建完的对象放到一个容器中,谁需要就给谁注入进去
Spring IOC环境搭建
-
创建Maven Project
-
配置Pom.xml文件
-课堂小练习:
-使用注解配置PersonService与PersonDao
- - -<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
SpringIOC入门代码测试
- 定义Person类 由spring创建并且赋值
- 创建容器
- 配置文件编写
new ClassPathXmlApplicationContext(“applicationContext.xml”); - 最后使用的getBean()从容器中取出
- Test01SpringIoc
private static final Logger log= LoggerFactory.getLogger(PersonService.class);
private ClassPathXmlApplicationContext context;
@Before
public void init(){
context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test01(){
// Person person2 = (Person) context.getBean("person2");
Person person2 = context.getBean("person2",Person.class);
log.debug(person2.toString());
}
- 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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 要让 spring容器给我创建一个person对象-->
<!-- 配置类名,用于反向创建对象-->
<!-- 同时给一个编号方便查找-->
<bean id="date1" class="java.util.Date"/>
<bean id="person" class="TestPack01.pojo.Person" />
<bean id="person2" class="TestPack01.pojo.Person">
<property name="id" value="2"/>
<property name="username" value="虎太郎2"/>
Spring面向接口原理
-
课堂前小练习:
怎么使用注解配置PersonService与PersonDao? -
(1)接口定义
业务类接口com.xxx.service.IXxxService
Dao接口 com.xxx.dao.IXxxDao -
(2)实现类
com.xxx.service.impl.XxxServiceImpl
com.xxx.dao.impl. XxxDaoImpl -
(3)一个接口有多个实现类,使用接口调用,将来更换实现类时,代码耦合底更低
判断方法:删除法 -
将来实现类对象由Spring管理,成员变量使用依赖注入
-
IPersonService
@Service
public class PersonService {
private static final Logger log= LoggerFactory.getLogger(PersonService.class);
@Autowired
PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public boolean login(Person per){
log.debug(per+"login");
Person person = personDao.find(per);
if (person == null){
return false;
}else {
return true;
}
}
}
- IPersonDao
@Repository
public class PersonDao {
public Person find(Person per) {
if("虎太郎".equals(per.getName())&&"12345".equals(per.getPassword())){
return per;
}else{
return null;
}
}
}
- applicationContext.xml
记得扫描注解
<context:component-scan base-package="TestPack01"/>
- TestPersonService
@Test
public void test07(){
//PersonService personService = new PersonService();
PersonService personService = (PersonService) context.getBean("personService");
Person p = new Person();
p.setName("虎太郎");
p.setPassword("12345");
boolean flag =personService.login(p);
log.debug(flag+"");
}
- 结果为: