Spring 利用IOC 对实现接口的解耦并且注解和xml对数据库的操作
半注解半xml
全注解
测试方法
半注解半xml (写的最少的方法)
- 配置环境,pom.xml 一些jar,然后就是配置dao、service 接口以及实现类,这里先不用controller。然后就是把三层中的两层用注解的形式进行连接:
半注解的形式时配置bean是用的是注解的约束条件
在配置bean是首先要扫描把类和包进行扫描<context:component-scan base-package=“com.itheima”/>就是把@[email protected]@[email protected]的类都加载到容器中。也就是为了自动找接口用的,还有找属性的值使用的(就是这个东西自动找的@Autowired)
然后就是在bean中配置queryrunner的信息 首先
然后测试方法现在有两种方法:
第一个就是不用注解的形式,还有一个就是用注解的形式。
-
不用注解的形式:
//获取容器对象
Classpathxmlapplicationcontext ca= new Classpathxmlapplicationcontext(“bean.xml”);
得到service实现类的对象,和面的.class是强制转换。
Ca.getbean(“accountservice”,IAccountService.class);
然后进行输出即可。 - 第二种就是注解的形式,
首先在pom中导入spring-test 然后就是
@runwith(“RunWith(“SpringJUnit4ClassRunner.class”)
@autowirired
//接口不用再写了,直接自动找就行了
AccountService accountservice;
全注解的形式(感觉写的很多)
全注解就是把半注解的bean.Xml改成一个类的形式在类里配置文件:
//在resources下写一个jdbc.properties文件
@PropertySource(“jdbc.properties”)
//就是把注解的类纳入容器中来使用
@ComponentScan(basePackages = “com.itheima”)
public class SpringConfiguratiom {
//配置四大参数
//然后就是利用连接池连接数据库
@Value("{jdbc.url}")
private String url;
@Value("{jdbc.password}")
private String password;
@Bean(“runner”)
@Scope(“prototype”)
public QueryRunner createrunner(DataSource dataSource)
{
return new QueryRunner(dataSource);
}
@Bean(“dataSource”)
public DataSource createDataSource()
{
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch (Exception e)
{
throw new RuntimeException(e);
}
}
源码在评论区,github上发布!