时间:2021-07-01 10:21:17 帮助过:30人阅读
//原理利用反射机制创建对象,调用带参构造器
<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()); } }
Spring 对象的获取,以及数据库连接应用
标签:auto com 数据库连接 -- 连接 cal ati roo 创建对象