黑马程序员技术交流社区
标题:
【石家庄校区】
[打印本页]
作者:
李志旭
时间:
2019-8-1 15:28
标题:
【石家庄校区】
Spring总结
一、IOC
1、spring基本坐标
<properties>
<spring.version>
5.0.5.RELEASE
</spring.version>
</properties>
<!--导入spring的context坐标,context依赖core、beans、expression-->
<dependencies>
<dependency>
<groupId>
org.springframework
</groupId>
<artifactId>
spring-context
</artifactId>
<version>
${spring.version}
</version>
</dependency>
</dependencies>
2、核心配置文件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"
xsi:schemaLocation
=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<!-- 将userDao注入到spring容器内,由spring容器管理-->
<bean
id
=
"userDao"
class
=
"com.itheima.dao.impl.UserDaoImpl"
></bean>
</beans>
3、使用Spring的API获得Bean实例
@Test
public
void
test1
(){
ApplicationContext
applicationContext
=
new
ClassPathXmlApplicationContext
(
"applicationContext.xml"
);
//UserDao userDao = (UserDao) applicationContext.getBean("userDao");
UserDao
userDao
=
(
UserDao
)
applicationContext
.
getBean
(
UserDao
.
class
);
userDao
.
save
();
}
4、Bean实例化三种方式
1)使用无参构造方法实例化(掌握)
<bean
id
=
"userDao"
class
=
"com.itheima.dao.impl.UserDaoImpl"
/>
2)工厂静态方法实例化(了解)
public
class
StaticFactoryBean
{
public
static
UserDao
createUserDao
(){
return
new
UserDaoImpl
();
}
}
<bean
id
=
"userDao"
class
=
"com.itheima.factory.StaticFactoryBean"
factory-method
=
"createUserDao"
/>
3)工厂实例方法实例化(了解)
public
class
DynamicFactoryBean
{
public
UserDao
createUserDao
(){
return
new
UserDaoImpl
();
}
}
<bean
id
=
"factoryBean"
class
=
"com.itheima.factory.DynamicFactoryBean"
/>
<bean
id
=
"userDao"
factory-bean
=
"factoryBean"
factory-method
=
"createUserDao"
/>
5、Bean的依赖注入(set方法)
1)在UserServiceImpl中添加setUserDao方法
public
class
UserServiceImpl
implements
UserService
{
private
UserDao
userDao
;
public
void
setUserDao
(
UserDao
userDao
) {
this
.
userDao
=
userDao
;
}
}
2)配置Spring容器调用set方法进行注入
<bean
id
=
"userDao"
class
=
"com.itheima.dao.impl.UserDaoImpl"
/>
<bean
id
=
"userService"
class
=
"com.itheima.service.impl.UserServiceImpl"
>
<property
name
=
"userDao"
ref
=
"userDao"
/>
</bean>
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2