勤敲代码
将创建对象的操作都交给Spring来完成
1.导入坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
2.创建Bean
domain
public class Cy {
private String cy_name;
private int price;
public String getCy_name() {
return cy_name;
}
public void setCy_name(String cy_name) {
this.cy_name = cy_name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Cy{" +
"cy_name='" + cy_name + '\'' +
", price=" + price +
'}';
}
}
Service接口
public interface CyService {
public List<Cy> menu();
}
实现类
public class CyServiceImpl implements CyService {
private CyDao cyDao;
public void setCyDao(CyDao cyDao) {
this.cyDao = cyDao;
}
public List<Cy> menu() {
return cyDao.menu();
}
}
Dao接口
public interface CyDao {
public List<Cy> menu();
}
实现类
public class CyDaoImpl implements CyDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Cy> menu() {
String sql = "select cy_name, price from cy";
return template.query(sql,new BeanPropertyRowMapper<Cy>(Cy.class));
}
}
这里数据库和表和数据就省略了,创建一个简单的就行了
3.接下来,创建配置文件
4.配置对应的关系
<?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">
<bean id="cyDao" class="com.trc.dao.impl.CyDaoImpl">
<property name="template" ref="template"></property>
</bean>
<bean id="CyService" class="com.trc.service.impl.CyServiceImpl">
<property name="cyDao" ref="cyDao"></property>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql://127.0.0.1:3306/lesson"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
</bean>
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
注意:数据库连接数据这里写死了,后期再做修改
5.测试
public class CyDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Cy.xml");
CyService cyService = (CyService) context.getBean("CyService");
List<Cy> cyList = cyService.menu();
System.out.println(cyList);
}
}
over~