标签:auto com 数据库连接 -- 连接 cal ati roo 创建对象
springioc编写规则:接收方注入,需要定义set方法或带参的构造器
//利用反射创建对象(无参构造器),利用反射机制注入参数
<bean id="calss="">
<property name="" value|ref=""></property>
</bean>
使用BasicDataSource进行数据库连接,数据库连接连接池,不用考虑创建,与释放连接。实现了DataSource接口
<bean id="dbcp" class="org.apache.commons.dbcp.BasicDataSource"> <property name="username" value="root"></property> <property name="password" value="123456"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/tracy"></property> </bean>
//原理利用反射机制创建对象,调用带参构造器
<bean id="calss="">
<constructor-arg index="" value|ref=""/>
</bean>
Spring对Jdbc进行了封装,JdbcTemplate依赖于DataSource
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg index="0" ref="dbcp"></constructor-arg> </bean>
一般使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
new BeanPropertyRowMapper<类型>(类型.class)
public class FanNews implements Serializable { public int id; public String fan_item; public String fan_name;
public interface FanNewsDao { public List<FanNews> loadAll(); }
@Repository("fanNewsDao") public class JdbcTemplateFanNews implements FanNewsDao { @Autowired private JdbcTemplate jdbcTemplate; public List<FanNews> loadAll() { String sql="select *from fan_news"; List<FanNews> list=jdbcTemplate.query(sql,new BeanPropertyRowMapper<FanNews>(FanNews.class)); for(FanNews news:list) { System.out.println(news.getFan_name()+news.getFan_item()); } return list; } }
<!-- 开启组件扫描可以识别以下标记 @Contorller @Service @Repository @Component@Resource @Autowired-->
<!-- 开启组件扫描 @Contorller @Service @Repository @Component@Resource @Autowired--> <context:component-scan base-package="com.tracy.dao.impl" />
@Test public void TestNewDao() { String config="com/tracy/xml/applicationContext.xml"; ApplicationContext acc=new ClassPathXmlApplicationContext(config); FanNewsDao fnd=acc.getBean("fanNewsDao",JdbcTemplateFanNews.class); List<FanNews> list=fnd.loadAll(); System.out.println(list); for(FanNews news:list) { System.out.println("注解标记读取接口"+news.getFan_name()+news.getFan_item()); } }
标签:auto com 数据库连接 -- 连接 cal ati roo 创建对象
原文地址:https://www.cnblogs.com/tracyDemo/p/13138781.html