spring5.0学习笔记6

本文详细解析了Spring框架中基于XML和注解的IOC(Inverse of Control)案例,包括配置文件定义、实体类、接口及实现类的创建,以及如何通过Spring容器管理和注入依赖。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于XML IOC案例
在这里插入图片描述

<?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"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">	


<bean id="stuService" class="com.test.StuServiceImp">
	<property name="stuDao" ref="stuDao"></property>
</bean>

<bean id="stuDao" class="com.test.StuDaoImp">
	<!-- set注入runner -->
	<property name="runner" ref="runner"></property>
</bean>

<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
	<constructor-arg index="0" ref="dataSource"></constructor-arg>
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/xiaonei"></property>
	<property name="user" value="root"></property>
	<property name="password" value="tingwei"></property>
</bean>

</beans>
package com.test;

import java.io.Serializable;

public class Stu implements Serializable{
	private String name;
	private Float score;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getScore() {
		return score;
	}
	public void setScore(Float score) {
		this.score = score;
	}
}
package com.test;

import java.util.List;

public interface IStuService{
	/**
	 * 查询所有
	 */
	List<Stu> findAllStu();
	
	Stu findStuByName(String name);
	void saveStu(Stu stu);
	void updateStu(Stu stu);
	void deleteStu(String name);
}
package com.test;

import java.util.List;

public interface IStuDao{
	List<Stu> findAllStu();
	
	Stu findStuByName(String name);
	void saveStu(Stu stu);
	void updateStu(Stu stu);
	void deleteStu(String name);
}
package com.test;

import java.util.List;

public class StuServiceImp implements IStuService{
	private IStuDao stuDao;
	public void setStuDao(IStuDao stuDao) {
		this.stuDao = stuDao;
	}

	public void deleteStu(String name) {
		// TODO Auto-generated method stub
		stuDao.deleteStu(name);
	}

	public List<Stu> findAllStu() {
		// TODO Auto-generated method stub
		return stuDao.findAllStu();
	}

	public Stu findStuByName(String name) {
		// TODO Auto-generated method stub
		return stuDao.findStuByName(name);
	}

	public void saveStu(Stu stu) {
		// TODO Auto-generated method stub
		stuDao.saveStu(stu);
	}

	public void updateStu(Stu stu) {
		// TODO Auto-generated method stub
		stuDao.updateStu(stu);
	}
	
}
package com.test;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class StuDaoImp implements IStuDao{
	private QueryRunner runner;
	public StuDaoImp(QueryRunner runner){
		this.runner = runner;
	}
	
	public StuDaoImp(){
		
	}
	public void deleteStu(String name) {
		// TODO Auto-generated method stub
		try {
			runner.update("delete from stu where id=?", name);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public List<Stu> findAllStu() {
		// TODO Auto-generated method stub
		try {
			return runner.query("select * from stu", new BeanListHandler<Stu>(Stu.class));
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public Stu findStuByName(String name) {
		// TODO Auto-generated method stub
		try {
			return runner.query("select * from stu where sname = ?", new BeanHandler<Stu>(Stu.class),name);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public void saveStu(Stu stu) {
		// TODO Auto-generated method stub
		try {
			runner.update("insert into stu(sname,score)values(?,?)",stu.getName(),stu.getScore());
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public void updateStu(Stu stu) {
		// TODO Auto-generated method stub
		try {
			runner.update("update stu set sname=?,score=? where sname=?",stu.getName(),stu.getScore(),stu.getName());
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}
	
	public void setRunner(QueryRunner runner) {
		this.runner = runner;
	}
	
}
/**
 * 基于XML的IOC案例
 */
package com.test;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{
    public static void main(String[] args){
    	//1.获取核心容器对象
    	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    	//2.根据id获取bean对象
    	IStuService stuService = (IStuService)ac.getBean("stuService",IStuService.class);
    //	List<Stu> stus= stuService.findAllStu();
    //	for(Stu stu:stus){
    //		System.out.println(stu.getName()+" "+stu.getScore());
    //	}
    	
    	Stu stu = (Stu)stuService.findStuByName("xiaohua");
    	System.out.println(stu.getName()+" "+stu.getScore());
    }
}
三月 25, 2020 3:04:55 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2a6ff: display name [org.springframework.context.support.ClassPathXmlApplicationContext@2a6ff]; startup date [Wed Mar 25 15:04:55 CST 2020]; root of context hierarchy 三月 25, 2020 3:04:55 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [bean.xml] 三月 25, 2020 3:04:55 下午 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@2a6ff]: org.springframework.beans.factory.support.DefaultListableBeanFactory@df8508 三月 25, 2020 3:04:55 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@df8508: defining beans [stuService,stuDao,runner,dataSource]; root of factory hierarchy 三月 25, 2020 3:04:55 下午 com.mchange.v2.log.MLog INFO: MLog clients using java 1.4+ standard logging. 三月 25, 2020 3:04:56 下午 com.mchange.v2.c3p0.C3P0Registry banner INFO: Initializing c3p0-0.9.2.1 [built 20-March-2013 11:16:28 +0000; debug? true; trace: 10] 三月 25, 2020 3:04:56 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager INFO: Initializing c3p0 pool... 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 -> 1hge15ya94kwam612jtrm|18dc649, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge15ya94kwam612jtrm|18dc649, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/xiaonei, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]

null 88.33

基于注解 IOC案例

<?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"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">	

<context:component-scan base-package="com.test"></context:component-scan>
<!-- 配置QueryRunner -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
	<!-- 注入数据源 -->
	<constructor-arg index="0" ref="dataSource"></constructor-arg>
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/xiaonei"></property>
	<property name="user" value="root"></property>
	<property name="password" value="tingwei"></property>
</bean>

</beans>
package com.test;

import java.io.Serializable;

public class Stu implements Serializable{
	private String name;
	private Float score;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Float getScore() {
		return score;
	}
	public void setScore(Float score) {
		this.score = score;
	}
}
package com.test;

import java.util.List;

public interface IStuService{
	/**
	 * 查询所有
	 */
	List<Stu> findAllStu();
	
	Stu findStuByName(String name);
	void saveStu(Stu stu);
	void updateStu(Stu stu);
	void deleteStu(String name);
}
package com.test;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("stuService")
public class StuServiceImp implements IStuService{
	@Autowired
	private IStuDao stuDao;
	
	public void deleteStu(String name) {
		// TODO Auto-generated method stub
		stuDao.deleteStu(name);
	}

	public List<Stu> findAllStu() {
		// TODO Auto-generated method stub
		return stuDao.findAllStu();
	}

	public Stu findStuByName(String name) {
		// TODO Auto-generated method stub
		return stuDao.findStuByName(name);
	}

	public void saveStu(Stu stu) {
		// TODO Auto-generated method stub
		stuDao.saveStu(stu);
	}

	public void updateStu(Stu stu) {
		// TODO Auto-generated method stub
		stuDao.updateStu(stu);
	}
	
}
package com.test;

import java.util.List;

public interface IStuDao{
	List<Stu> findAllStu();
	
	Stu findStuByName(String name);
	void saveStu(Stu stu);
	void updateStu(Stu stu);
	void deleteStu(String name);
}
package com.test;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("stuDao")
public class StuDaoImp implements IStuDao{
	@Autowired
	private QueryRunner runner;
	public StuDaoImp(QueryRunner runner){
		this.runner = runner;
	}
	
	public StuDaoImp(){
		
	}
	public void deleteStu(String name) {
		// TODO Auto-generated method stub
		try {
			runner.update("delete from stu where id=?", name);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public List<Stu> findAllStu() {
		// TODO Auto-generated method stub
		try {
			return runner.query("select * from stu", new BeanListHandler<Stu>(Stu.class));
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public Stu findStuByName(String name) {
		// TODO Auto-generated method stub
		try {
			return runner.query("select * from stu where sname = ?", new BeanHandler<Stu>(Stu.class),name);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public void saveStu(Stu stu) {
		// TODO Auto-generated method stub
		try {
			runner.update("insert into stu(sname,score)values(?,?)",stu.getName(),stu.getScore());
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public void updateStu(Stu stu) {
		// TODO Auto-generated method stub
		try {
			runner.update("update stu set sname=?,score=? where sname=?",stu.getName(),stu.getScore(),stu.getName());
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}
	
	public void setRunner(QueryRunner runner) {
		this.runner = runner;
	}
	
}
/**
 * 基于注解的IOC案例
 */
package com.test;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test{
    public static void main(String[] args){
    	//1.获取核心容器对象
    	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    	//2.根据id获取bean对象
    	IStuService stuService = (IStuService)ac.getBean("stuService",IStuService.class);
    //	List<Stu> stus= stuService.findAllStu();
    //	for(Stu stu:stus){
    //		System.out.println(stu.getName()+" "+stu.getScore());
    //	}
    	
    	Stu stu = (Stu)stuService.findStuByName("xiaohua");
    	System.out.println(stu.getName()+" "+stu.getScore());
    }
}
三月 25, 2020 3:10:46 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2a6ff: display name [org.springframework.context.support.ClassPathXmlApplicationContext@2a6ff]; startup date [Wed Mar 25 15:10:46 CST 2020]; root of context hierarchy 三月 25, 2020 3:10:46 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [bean.xml] 三月 25, 2020 3:10:46 下午 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@2a6ff]: org.springframework.beans.factory.support.DefaultListableBeanFactory@2f9028 三月 25, 2020 3:10:46 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2f9028: defining beans [stuDao,stuService,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,runner,dataSource]; root of factory hierarchy 三月 25, 2020 3:10:46 下午 com.mchange.v2.log.MLog INFO: MLog clients using java 1.4+ standard logging. 三月 25, 2020 3:10:46 下午 com.mchange.v2.c3p0.C3P0Registry banner INFO: Initializing c3p0-0.9.2.1 [built 20-March-2013 11:16:28 +0000; debug? true; trace: 10] 三月 25, 2020 3:10:47 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager INFO: Initializing c3p0 pool... 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 -> 1hge15ya94l3t781j1xm2x|7016ff, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge15ya94l3t781j1xm2x|7016ff, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/xiaonei, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]

null 88.33

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值