文章目录
1 Spring 调用JDBC
1.dao接口
2.dao接口实现类impl
3.数据库对应POJO类
4.控制器console
5.spring XML配置文件
- 引入两个maven包(pom.xml)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.15.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
- dao接口:
public interface SelectUserDao {
LoginUser selectUser(int userId);
}
- 然后是dao接口实现类:
public class SelectUserDaoImpl implements SelectUserDao {
private DataSource dataSource;
private String sql;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
@Override
public LoginUser selectUser(int userId) {
LoginUser loginUser = new LoginUser();
try {
System.out.println(sql);
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, userId);
ResultSet rs = statement.executeQuery();
rs.next();
loginUser.setId(rs.getString("id"));
loginUser.setUserName(rs.getString("username"));
loginUser.setPassword(rs.getString("password"));
rs.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return loginUser;
}
}
- POJO数据模型:
public class LoginUser {
private String id;
private String userName;
private String password;
} // getter,setter
- 最后spring.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/admin?useSSL=false" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
<bean id="selectUserDaoImpl" class="dao.SelectUserDaoImpl">
<property name="dataSource" ref="dataSource" />
<property name="sql" value="select id,username,password from user where id=?" />
</bean>
- 测试类
public class TestPojo {
static ApplicationContext context;
@BeforeClass
static public void getXMl() {
context = new ClassPathXmlApplicationContext("spring3.xml");
}
@AfterClass
static public void close() {
System.out.println("---测试结束---");
}
@Test
public void getObject(){
SelectUserDaoImpl selectUserDao = context.getBean("selectUserDaoImpl",SelectUserDaoImpl.class);
LoginUser user =selectUserDao.selectUser(1);
System.out.println(user.getId());
System.out.println(user.getUserName());
}
}
1.1 JdbcDaoSupport管理JDBC
Spring官方并不建议我们直接使用jdbc来处理增删改查,而是使用Spring封装好的一个类JdbcDaoSupport来管理,这样代码更简练,更容易维护。
JdbcDaoSupport类中自带dataSource属性,Spring会注入到此属性中,所以我们的Impl类中不再需要这个属性,只需要继承JdbcDaoSupport和自己的dao接口就可以了,也就是基于上面的例子中,我们仅仅只需要修改Impl类的代码,其余都不做修改,来看看修改后的Impl代码如下:
public class SelectUserDaoImpl extends JdbcDaoSupport implements SelectUserDao {
private String sql;
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public LoginUser selectUser(int userId) {
/* 通过JdbcDaoSupport中的getJdbcTemplate的query方法进行查询
BeanPropertyRowMapper传入指定表对应的POJO对象,spring做反射自动封装
并且返回一个指定POJO类型的 list 因为我们基于id查询只会返回一条记录,
所以get(0)*/
return getJdbcTemplate().query(sql,
new Object[]{userId}, new BeanPropertyRowMapper<>(LoginUser.class)).get(0);
}
}
是不是变得简洁了,增加了可读性,如果项目中没有数据库对应的框架,我们就可以用这种模式来进行spring对jdbc的管理
这里其实只对JdbcDaoSupport做了简单的使用,如果有兴趣可以查询更多JdbcDaoSupport的使用资料。
2 xml中其他属性
2.1 单实例和多实例模式的切换(scope)
每一个bean标签中都有scope属性,此属性默认存在并且为singleton,也就是单实例,手动修改为prototype之后变成多实例(多实例的时候,spring默认管理方式是懒加载)。
2.2 懒加载模式和预加载模式(lazy-init)
Spring默认是预加载模式,也就是lazy-init值默认为false,在下面代码初始化完成,所有的bean都会被初始化
String[] xmlNameArray = {“spring-config.xml”};
ApplicationContext context = new ClassPathXmlApplicationContext(xmlNameArray);
这样的好处在于spring随服务启动的时候,所有bean初始化完成,为后续操作提升执行效率,如果手动修改为true,启动的时候,不会初始化bean。我们可以通过在bean的构造函数中打印一句话来证明这件事情。
2.3 定义初始化(init-method)和销毁(destroy-method)方法
<bean name="oneBean" class="beans.OneBean"
init-method="initMethod" destroy-method="desMethod"/ >
在bean直接定义init方法和destroy方法,这样在spring初始化这个对象的时候,会自动调用init指定的方法,在ApplicationContext关闭的时候,会调用destroy指定的方法。初始化的方法,可以让我们在开发中手动构建一些指定的逻辑代码,虽然有了spring,大部分时候不需要这么做,但是spring还是预留了此方式,destroy方法可以在spring关闭前,手动处理释放资源。
2.4 自动装配(autowire)
Autowire默认值为no,代表不自动装配,所以前面我们都是手动配置。
PS:这种模式并不适用于项目中的工厂模式,因为工厂中一个父接口可以接收不同的子类型对象。
Autowire还有一种是autowire=“byType”,代表自动查找属性的类型完成自动装配。
PS:在这里需要说明,自动创建配置内容看起来更加简练了,但是可读性取大大降低,项目之中尽可能不要使用自动装配,避免增加阅读复杂度。
3 注解
注解 | 说明 | 描述 |
---|---|---|
@Componet | 把此类放入bean容器中 | 在类上面写,相当于 |
@Autowired | 自动装载 | 在方法上写 |
@Service | 服务 | 在ServiceImpl上写 |
@Controller | 控制器 | 在控制器类上写 |
@Scope(“prototype”) | 默认多实例(单实例) | |
@Lazy(true) | 使用时加载 | |
@transaction | 事务 |
3.1 注解自动装配
定义两个bean对象,然后在twobean中注入onebean对象,注意xml中需要增加少许内容:
1.增加context的支持
xmlns:context="http://www.springframework.org/schema/context"
2.增加xml标签的验证
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"
3.增加自动装配属性
<context:annotation-config />
最后我们只需要在TwoBean中通过@Autowired进行注解
这里主要建议使用属性注解,因为属性注解,可以删除set方法,让代码看起来更加简练
如果属性是父类型,那么自动注解无法完成装载,这时候需要通过@Qualifier(“oneBean”)的注解来指定需要装载进来的bean对象的name
还可以像下面的下面这样定义:
@Autowired
public void prepare(@Qualifier(“myid”)ClassBean classBean) {
//…
}