Spring_06_基于注解的IOC-component注解

博客介绍了Java后台使用Spring框架时的组件配置方法,一是在bean.xml中添加特定行,二是在类上方写上@Component,帮助开发者完成组件配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在bean.xml中加上以下几行

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:http="http://www.springframework.org/schema/c"
       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">

    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,
        而是一个名称为context名称的空间和约束中-->
    <context:component-scan base-package="com.itheima"></context:component-scan>


</beans>

2.在类上方写上@Component

package com.itheima.service.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.IAccountService;
import org.springframework.stereotype.Component;
/**
 * 账户业务实现类
 *
 * 曾经的XML配置
 * <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *      scope="" init-method="" destory-method="">
 *      <property name="" value="" | ref=""></property>
 * </bean>
 *
 * 用于创建对象的注解
 *      作用和在XML中写<bean></bean>标签是一样的
 *      Component:
 *          作用:用于把当前对象存入spring中
 *          属性:value用于指定bean的id.不写时,默认是当前类名,且首字母小写
 * 
 *      Controller:一般用在表现层
 *      Service:一般用在业务层
 *      Repository:一般用在持久层
 *      以上三个注解的作用和属性与Component一模一样
 *      他们三个是spring框架为我们提供的明确的三层使用的注解,使我们三层对象更加清晰
 */
//@Component
@Component(value="accountService")//只有一个属性时,value可以省略
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao = new AccountDaoImpl();
    public AccountServiceImpl(){
        System.out.println("AccountServiceImpl创建了");
    }

    public void saveAccount() {
        accountDao.saveAccount();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值