public interface UserDao {
public void save();
}
public interface BookDao {
void save();
}
public interface BookService {
void save();
}
public class UserDaoImpl implements UserDao{
public void save(){
System.out.println("user dao save ...");
}
}
public class BookDaoImpl implements BookDao{
public void save(){
System.out.println("book dao save");
}
}
public class BookServiceImpl implements BookService {
//删除业务层中使用new的方式创建的dao对象
private BookDao bookDao;
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
//生成set方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void save(){
System.out.println("book service save ...");
bookDao.save();
userDao.save();
}
}
<bean id ="bookDao" name = "dao" class = "com.itheima.dao.impl.BookDaoImpl" scope="prototype"/>
<bean id = "userDao" class="com.itheima.dao.impl.UserDaoImpl"/>
<bean id = "bookService" name = "service bookEbi" class = "com.itheima.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
<property name="userDao" ref="userDao"/>
bean>
public class App2 {
public static void main(String[] args) {
//3.获取IoC容器,ApplicationContext和配置一样,new一个接口实现类
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService) ctx.getBean("bookService");
bookService.save();
}
}
book service save ...
book dao save
user dao save ...
Process finished with exit code 0
public class BookDaoImpl implements BookDao{
private int connectionNum;
private String databaseName;
public void setConnectionNum(int connectionNum) {
this.connectionNum = connectionNum;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public void save(){
System.out.println("book dao save"+databaseName+","+connectionNum);
}
}
<bean id ="bookDao" name = "dao" class = "com.itheima.dao.impl.BookDaoImpl">
<property name="databaseName" value="mysql"/>
<property name="connectionNum" value="10"/>
bean>
book service save ...
book dao savemysql,10
user dao save ...
Process finished with exit code 0
public class BookDaoImpl implements BookDao{
public void save(){
System.out.println("book dao save");
}
}
public class UserDaoImpl implements UserDao{
public void save(){
System.out.println("user dao save ...");
}
}
public class BookServiceImpl implements BookService {
//删除业务层中使用new的方式创建的dao对象
private BookDao bookDao;
private UserDao userDao;
//private BookDao bookDao = new BookDaoImpl();
//去掉setter方法,进行构造方法构造依赖,记得整两
public BookServiceImpl(BookDao bookDao, UserDao userDao) {
this.bookDao = bookDao;
this.userDao = userDao;
}
public void save(){
System.out.println("book service save ...");
bookDao.save();
userDao.save();
}
}
public class App2 {
public static void main(String[] args) {
//3.获取IoC容器,ApplicationContext和配置一样,new一个接口实现类
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService) ctx.getBean("bookService");
bookService.save();
}
}
<bean id ="bookDao" name = "dao" class = "com.itheima.dao.impl.BookDaoImpl"/>
<bean id ="userDao" name = "dao" class = "com.itheima.dao.impl.UserDaoImpl"/>
<bean id = "bookService" class = "com.itheima.service.impl.BookServiceImpl">
<constructor-arg name="bookDao" ref="bookDao"/>
<constructor-arg name="userDao" ref="userDao"/>
bean>
这边的name表示构造器的形参
也是用的构造器实现的
public class BookDaoImpl implements BookDao{
private String databaseName;
private int connectionNum;
public BookDaoImpl(String databaseName, int connectionNum) {
this.databaseName = databaseName;
this.connectionNum = connectionNum;
}
public void save(){
System.out.println("book dao save"+databaseName+connectionNum);
}
}
这两顺序可以换
<bean id ="bookDao" class = "com.itheima.dao.impl.BookDaoImpl">
<constructor-arg name="databaseName" value="mysql"/>
<constructor-arg name="connectionNum" value="666"/>
bean>
book service save ...
book dao savemysql666
user dao save ...
Process finished with exit code 0
如果构造器的形参变了,配置文件就得重新配置,出现耦合度比较高的情况,
因此可以直接写类型,不直接指定形参
<bean id ="bookDao" class = "com.itheima.dao.impl.BookDaoImpl">
<constructor-arg type="java.lang.String" value="mysql"/>
<constructor-arg type="int" value="10"/>
bean>
但是也可能出现两种类型一样的形参
于是出现了通过index需要指定
<bean id ="bookDao" class = "com.itheima.dao.impl.BookDaoImpl">
<constructor-arg index="0" value="mysql"/>
<constructor-arg index="1" value="100"/>
bean>
IoC容器根据bean所依赖的资源在容器中自动查找并注入到bean中的过程称为自动装配
依旧记得保留setter方法
public class BookServiceImpl implements BookService {
//删除业务层中使用new的方式创建的dao对象
private BookDao bookDao;
// private BookDao bookDao = new BookDaoImpl();
//生成set方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void save() {
System.out.println("book service save ...");
bookDao.save();
}
}
加上autowire就可以了
<bean id ="bookDao" class = "com.itheima.dao.impl.BookDaoImpl" scope="prototype"/>
<bean id = "bookService"
class = "com.itheima.service.impl.BookServiceImpl" autowire="byType"/>
BookServiceImpl中的BookDao与配置文件中的bookDao中bean实现了Dao接口,如果没有就报错
也就是说是private BookDao bookDao中的BookDao 和 如果满足接口的Dao接口的有两个,就会装配失败 private BookDao bookDao中的bookDao和id ="bookDao"中的bookDao名字要一样,耦合度较高 autowire="byName 第三方的bean该如何管理 Druid是阿里巴巴开发的数据连接池 发现DruidDataSource中有setter方法 网址:去Maven Repository: c3p0 » c3p0 » 0.9.1.2 (mvnrepository.com)复制代码 网址:Maven Repository: mysql » mysql-connector-java » 5.1.16 (mvnrepository.com) 需要让spring可以读取识别properties的文件 可以用,或者用* 使用classpath表示类路径 使用classpath*表示可以从本工程,或者以及依赖的jar包中读取
5.3.2 按照byName匹配
<bean id ="bookDao" class = "com.itheima.dao.impl.BookDaoImpl" scope="prototype"/>
<bean id = "bookService" class = "com.itheima.service.impl.BookServiceImpl" autowire="byName"/>
5.3.3 总结
6 集合注入
6.1 内容
6.2 配置内容
public class BookDaoImpl implements BookDao{
private int[] array;
private List<String> list;
private Set<String> set;
private Map<String,String> map;
private Properties properties;
public void setArray(int[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void save(){
System.out.println("book dao save");
System.out.println("遍历数组:"+ Arrays.toString(array));
System.out.println("遍历List:"+list);
System.out.println("遍历Set:"+set);
System.out.println("遍历Map:"+map);
System.out.println("遍历Properties:"+properties);
}
}
<bean id ="bookDao" name = "dao" class = "com.itheima.dao.impl.BookDaoImpl">
<property name="array">
<array>
<value>100</value>
<value>200</value>
<value>300</value>
<ref bean="beanId"/>
</array>
</property>
<property name="list">
<list>
<value>itcast</value>
<value>itheima</value>
<value>boxuegu</value>
<value>chuanzhihui</value>
</list>
</property>
<property name="set">
<set>
<value>itcast</value>
<value>itheima</value>
<value>boxuegu</value>
</set>
</property>
<property name="map">
<map>
<entry key="country" value="china"/>
<entry key="province" value="guangdong"/>
<entry key="city" value="guangzhou"/>
</map>
</property>
<property name="properties">
<props>
<prop key="country">china</prop>
<prop key="province">guangdong</prop>
<prop key="city">guangzhou</prop>
</props>
</property>
</bean>
7 第三方bean注入:以数据源对象管理为例
7.1 概述
7.2 Druid管理
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.16version>
dependency>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_db"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
bean>
public class App2 {
public static void main(String[] args) {
//3.获取IoC容器,ApplicationContext和配置一样,new一个接口实现类
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource);
}
}
{
CreateTime:"2022-11-06 23:08:56",
ActiveCount:0,
PoolingCount:0,
CreateCount:0,
DestroyCount:0,
CloseCount:0,
ConnectCount:0,
Connections:[
]
}
7.3 C3P0连接池管理
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.16version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.16version>
dependency>
<bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_db"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
public class App2 {
public static void main(String[] args) {
//3.获取IoC容器,ApplicationContext和配置一样,new一个接口实现类
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) ctx.getBean("dataSource2");
System.out.println(dataSource);
}
}
com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge1adasl3sdda8tlh5w|76b0bfab, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge1adasl3sdda8tlh5w|76b0bfab, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/spring_db, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
8 加载properties文件
8.1 概述
8.2 操作
<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:property-placeholder location="jdbc.properties"/>
<bean class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root
<bean id = "bookDao" class="com.itheima.dao.impl.BookDaoImpl">
<property name="name" value="${jdbc.driver}"/>
bean>
public class App2 {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
}
}
book dao savecom.mysql.jdbc.Driver
Process finished with exit code 0