spring基于注解方式实现对象的注入

1、什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值…)
(2)使用注解,注解作用在类上面,方法上面,属性上面·
(3)使用注解目的:简化xml配置
2、Spring针对Bean管理中创建对象提供注解
(1) @Component.
(2)@Serviceu
(3) @Controller
(4)@Repository
第一步引入依赖·
第二步开启组件扫描·
第三步创建类,在类上面添加创建对象注解

<?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"

       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">
        
<context:component-scan base-package="cn.zsp.spring5"></context:component-scan>
</beans>

使用到的类:

package cn.zsp.spring5.service;

import org.springframework.stereotype.Component;

@Component
public class UserService {
    public void show(){
        System.out.println("成功使用注解");
    }
}

测试类:


    public  void test1(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.show();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值