Spring框架第二天知识总结

一:DBCP与C3P0连接池的区别

DBCP通过BasicDataSource创建连接池对象,而C3P0通过ComboPooledDataSource创建连接池对象

步骤都是一样的:

//创建一个连接池对象!!
BasicDataSource dataSource = new BasicDataSource(); 或者:
ComboPooledDataSource dataSource = new ComboPooledDataSource

//设置四大配置信息传入dataSource 中
String driverClass="com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/数据库名?characterEncoding=utf8";
String username = "数据库用户名";
String password = "数据库密码";
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);

// 创建DBUtils 核心类 QueryRunner对象把dataSource 传进去
QueryRunner queryRunner = new QueryRunner(dataSource);
//执行sql语句 处理数据
String sql = "select * from account";
List<Account> list = queryRunner .query(sql, new BeanListHandler<>(Account.class));
if(list!=null && list.size()>0){
for (Account account : list) {
System.out.println(account);
}
}

二:注解

1.注意:想要用注解必须先在xml中扫描注解(添加context约束)
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<!--开启spring扫描约束-->
<context:component-scan base-package="要扫描的包"/>

<context:property-placeholder location="classpath:properties配置文件"/>
property-override: 读取properties文件
location=下有两种获取properties配置文件的方式:
classpath: :在当前路径下查找properties文件
classpath* :除了当前文件下找 还去引入的jar包下找 maven高级应用

2.@Component:创建实现类对象 英文组件的意思
例:@Component:("accountservice") = <bean id="accountService" class="com.itheima.service.AccountServiceImpl"></bean>

3.Spring为了更好的区分三层结构 @Component注解在三层中还可以换一种注解方式
@Controller : 控制web层类中的注解
@Service : 控制在service层中类的注解
@Repository : 控制在dao层中类的注解

4.Scope注解属性 :单例,多例 默认数单例模式 多例需要@Scope("prototype")

5.init-method构造执行以后执行方法 destory-method对象销毁之前执行: 必须用在方法上
@PostConStruct 构造执行以后执行
@PreDestroy 对象销毁之前执行

三:依赖注入的注解(分为String依赖注入和jdk依赖注入,建议使用String依赖注入)

1.@Autowired 英文 自动穿戴的意思 String提供
@Qualifier("关联的id") 不写关联的id默认是类名的小写 建议写上关联的id
@Autowired与 @Qualifier("关联的id")连用实现注解注入 不需要写setXXX方法

2.@Resource(name =" ") jdk提供

四:junit测试:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml");
AccountService accountService = context.getBean("accountService", AccountService.class);
每次测试都要写以上代码 解决这一问题的步骤 1.需要导包2.加入注解,3.读取配置文件

导包: 需要注意的是要和sping导包的版本是一个版本
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>

提取service,加入注解:@RunWith(SpringJUnit4ClassRunner.class)

读取配置文件:@ContextConfiguration(locations = "classpath:xml配置文件")
@ContextConfiguration(locations = "classpath:xml配置文件") 等同于ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml");

猜你喜欢

转载自www.cnblogs.com/lgpliuguoping/p/11449040.html