Spring IoC、DI入门小程序

Alt+/智能提示xml配置文件节点及属性;在接口上使用Ctrl+T可以提示其实现类

一、IoC控制反转(将创建对象的权利交给spring)入门小程序

1、引入jar包

Spring IoC、DI入门小程序

2、工程基本结构

Spring IoC、DI入门小程序

3、新建UserService类

package hjp.spring.demo1;

import org.junit.Test;

public class UserService {
public void addUser() {
System.out.println("addUser");
}
}

4、新建beans.xml文件配置bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userServiceId" class="hjp.spring.demo1.UserService"></bean>
</beans>

5、新建测试类TestApp

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp {
@Test
public void demo1() {
// 1、加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("hjp/spring/demo1/beans.xml");
// 2、从Spring工厂获得对象
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
}
}

二、DI依赖注入(自动实例化类中属性对象)入门小程序

1、沿用上面工程

2、新增包,结构如下

Spring IoC、DI入门小程序

3、新建BookDao类

package hjp.spring.demo2;

public class BookDao {
public void save() {
System.out.println("save book");
}
}

4、新建BookService类

package hjp.spring.demo2;

public class BookService {
private BookDao bookDao; public BookDao getBookDao() {
return bookDao;
} public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
} public void addBook() {
bookDao.save();
}
}

5、新建beans.xml文件配置bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 创建dao -->
<bean id="bookDaoId" class="hjp.spring.demo2.BookDao">
</bean>
<!-- 创建service -->
<bean id="bookServiceId" class="hjp.spring.demo2.BookService">
<!-- <property>进行依赖注入过程,底层将执行setter方法
name 指BookService类bookDao属性
ref 指属性实例引用
-->
<property name="bookDao" ref="bookDaoId"></property>
</bean>
</beans>

6、新建测试类TestAPP

package hjp.spring.demo2;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp {
@Test
public void demo1() {
//获得容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("hjp/spring/demo2/beans.xml");
//获得对象
BookService bookService = applicationContext.getBean("bookServiceId", BookService.class);
bookService.addBook();
}
}
上一篇:appium+python 微信小程序的自动化


下一篇:Web Api 2 接口API文档美化