1.注解创建对象
(1)在spring配置文件中开启注解扫描
<context:component-scan base-package="com.melon"></context:component-scan>
(2)在需要创建对象的类上面进行注解,需要注意的是注解标签有Component、Service、Controller和Repository
@Component(value="userDao")
public class UserDao{}
(3)得到对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userDao");
2.注解注入属性
(1)开启注解扫描
(2)在需要创建对象的类上面注解
(3)注入属性
public class UserService {
@Autowired
//可以用Resuource(name="userDao"),但是name里面的属性值要和注解id相同
private UserDao userDao;
userdao.add();
}
3.aop增强
(1)先创建被增强类和增强类
<bean id="userService" class="com.melon.aop.UserService"></bean>
<bean id="userService1" class="com.melon.aop.UserService1"></bean>
(2)在配置文件中配置切入点和切面
<aop:config>
//表达式写法 execution(修饰符 方法全路径(局部变量))
<aop:pointcut expression="execution(* com.melon.aop.UserService.print(..))" id="pointcut1"/>
<aop:aspect ref="userService1">
//此处除before可以选择多种方式
<aop:before method="print" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
//配置完成后调用userService的print方法时,会先调用userService1的print方法
4.使用JdbcTemplate
(1)增加
public void add() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("1");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "insert into user (name,password) values (?,?)";
jdbcTemplate.update(sql, "melon","1");
}
(2)查询值
public void search() {
String sql = "select password from user where name=?";
String password = jdbcTemplate.queryForObject(sql, String.class, "melon");
System.out.println(password);
}
(3)查询对象
public void searchForObject() {
String sql = "select * from user where name=?";
User user = (User) jdbcTemplate.queryForObject(sql, new myRowMapper(), "melon");
System.out.println(user);
}
//查询对象或集合时,需要实现RowMapper接口
class myRowMapper implements RowMapper<User>{
public User mapRow(ResultSet rs, int count) throws SQLException {
User user = new User();
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
return user;
}
}
(4)查询集合,同样需要实现RowMapper接口
public void searchForList() {
String sql = "select * from user";
List<User> user = jdbcTemplate.query(sql, new myRowMapper());
System.out.println(user);
}
5.使用c3p0连接池
(1)配置dataSource信息
<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/test"></property>
<property name="user" value="root"></property>
<property name="password" value="1"></property>
</bean>
(2)将dataSource注入jdbcTemplate
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>