我爱Java系列---【Spring基于半注解、半xml的 IOC 配置】

总结:

  • 使用注解的前提:在配置文件中,声明需要扫描的包的路径,base-package可以写大包名,也可以用逗号分开写需要扫描的包名(考虑扫描速度,推荐分开写)

     配置 spring 创建容器时要扫描的包:

                                  

  <context:component-scan base-package="com.it.service,com.it.dao"></context:component-scan>

 

 

复制代码
 前存后取,用的时候前后各挑一个就可以了,没有对应关系

(存到spring容器中,默认存的类名) (取的时候用类型获取)   
1.@Component * *@Resource(type = AccountService.class) 不常用   2.@Service * *@Resource(name = "accountServiceImpl") 不常用   3.@Repository * *@Autowired 常用,根据类型匹配,写在哪个声明变量前就代表谁 ,
                                前提:仅有一个该类型的对象
若有多个实现类,可以
                                使用@Qualifier("accountDaoImpl")

  4.@Controller *
复制代码

 

 

复制代码
 前存后取,用的时候前后各挑一个就可以了,没有对应关系

(存到spring容器中,自定义名字) (取的时候用自定义名字获取)
  
1.@Component("accountService") *   2.@Service("accountService") * *@Resource(name = "accountService") 不常用   3.@Repository("accountDao") * *@Autowired 常用,写在哪个声明变量前就代表谁 ,
                                        前提:仅有一个该类型的对象


  4.@Controller("accountServlet") *
复制代码

 

常用:@Service和@Autowired (重点掌握就够了)

配置文件中用name=$(name),把配置文件中的name传递给java

(学会这个流程就会用半注解、半配置文件配置spring了)  

 1.引入外部属性文件:可以引入多个,逗号分割

    

<context:property-placeholder location="classpath:db.properties,classpath:hh.properties">
</
context:property-placeholder>
//注意:properties文件中不能有中文,要想传递中文,先使用unicode在线编码转码,再使用就行了

 2.获取外部文件中的内容  
    

1 <bean id="message" class="com.itheima.utils.MessageUtil">
2    <property name="name" value="${name}"/>
3 </bean>

 

3.用@Component把MessageUtil类放入spring容器,其他类调用时用@Autowired去取,

  下面声明方法类型和方法名,获得MessageUtil类对象后,就可以调用里面的方法了。

 

 

一、环境搭建(以下代码仅供练习使用

  1.创建 maven 工程quickstart,并导入坐标

复制代码
pom.xml 中的依赖:
<dependencies>
<!-- junit单元测试 -->

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--spring整合测试类-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>

<!-- spring框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- dbutils
DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码。
org.apache.commons.dbutils
DbUtils 关闭链接等操作
QueryRunner 进行查询的操作
org.apache.commons.dbutils.handlers 处理结果集

-->
  <dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>

<!-- mysql驱动-->
  <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
复制代码

2.创建数据库和编写实体类

//创建数据库
create table account ( id int auto_increment primary key, name varchar(32) , password varchar(32), money int );
复制代码
//编写实体类
public class Account { private long id; private String name; private String password; private long money; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public long getMoney() { return money; } public void setMoney(long money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", money=" + money + '}'; } }
复制代码

3.编写持久层代码

复制代码
//定义接口
public interface AccountDao { //1.增加账户 public int save(Account account); //2.根据id查询账户 public Account findById(int id); }
复制代码
复制代码
//编写实现类

//@Component("accountDao") //把下面这个类放到spring容器中,谁需要就用@Resource(name="accountDao")去取

@Repository("accountDao") //Repository持久化的意思,这个用法和@Component("accountDao")一个作用,但只能用在dao层
public class AccountDaoImpl implements AccountDao {

@Resource(name="queryRunner") //1.从spring容器中取出queryRunner对象,当你使用注解的方式注入对象,不需要写set方法,
                      因为配置文件属性注入方式底层采用调用setter方法,而注解方式底层采用暴力反射
//2.此处应当注意,queryRunner来自第三方,配置文件中的声明不可省略,连接数据库的声明也不可省略
//3.注意:@Resource(name="queryRunner") 必须要写在声明变量之前,即下面这句话
                      之前,private QueryRunner queryRunner;的前面,否则报错

private QueryRunner queryRunner; /* public void setQueryRunner(QueryRunner queryRunner) { this.queryRunner = queryRunner; }*/ //1.增加账户 public int save(Account account){ String sql ="insert into account values (null,?,?,?) "; try { return queryRunner.update(sql,account.getName(),account.getPassword(),account.getMoney()); } catch (SQLException e) { throw new RuntimeException(e); } } //2.根据id查询账户信息 @Override public Account findById(int id) { String sql ="select * from account where id=?"; try { return queryRunner.query(sql,new BeanHandler<>(Account.class),id); } catch (SQLException e) { throw new RuntimeException(e); } } }
复制代码

4.编写业务层代码

复制代码
//定义接口
public interface AccountService {

    //1.增加账户
    public int save(Account account);

    //2.根据id查询账户信息
    public Account findById(int id);
}
复制代码
复制代码
//编写实现类
//@Component("accountService ") //把下面这个类放到spring容器中,谁需要就用@Resource(name="accountService ")去取

@Service("accountService")  //和@Component("accountService ")的作用一样,但只能用在service层
 public class AccountServiceImpl implements AccountService {

@Resource(name="accountService ") //1.从spring容器中取出accountService对象,当你使用注解的方式注入对象,不需要写set方法,
因为配置文件属性注入方式底层采用调用setter方法,
而注解方式底层采用暴力反射
private AccountDao accountDao;
/*public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } */

//1.增加账户

@Override
public int save(Account account) { return accountDao.save(account); }

//2.根据id查询账户
@Override
public Account findById(int id) { return accountDao.findById(id); } }
复制代码

二、创建配置文件

1.创建配置文件并导入约束

复制代码
<?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
                "

> <!--分析:service - dao - queryRunner - dateSource,从后往前配 --> <!--1.配置dateSource--> <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="jdbc:mysql:///heima?characterEncoding=utf-8"/> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--2.配置queryRunner--> <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"> <constructor-arg name="ds" ref="dateSource"></constructor-arg> </bean> <!-- <!--3.配置AccountDao--> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"> <property name="queryRunner" ref="queryRunner"/> </bean> <!--4.配置AccountService,并解决依赖注入--> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> <property name="accountDao" ref="accountDao"/> </bean>--> </beans>
复制代码

三、测试代码

 

复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:beans.xml")
public class AccountTest {
    @Autowired
    private AccountService accountService;

//1.增加账户

@Test public void testSave() {
Account account = new Account();
account.setId(2); account.setName("亚瑟");
account.setPassword("yuji");
account.setMoney(3000);
int i = accountService.save(account);
if (i == 1) { System.out.println("添加账户成功"); } else { System.out.println("添加账户失败"); } }

 //2.根据id查询账户信息
@Test public void testFindById(){
Account accountById = accountService.findById(2);
System.out.println(accountById);
}
}
复制代码

 

至此,增和查的功能已经完成,删改功能同理可得。

 

posted on   少年攻城狮  阅读(483)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示