java使用注解开发_Spring-使用注解开发(十二)

本文介绍了Spring框架中注解开发的步骤,包括导入相关包、配置扫描组件、编写带有注解的类以及测试代码。同时,展示了如何使用@Value注解进行IOC注入,比较了注解与XML配置的优缺点。注解简化了配置,但存在局限性,而XML配置则更为通用。
摘要由CSDN通过智能技术生成

1.使用注解开发需要导入spring的一系列包;

2.需要再配置文件中加一个约束:context;

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd

3.配置扫描组件

4.编写代码

package org.west.pojo;

import org.springframework.stereotype.controller;

@controller("stu")

public class student {

public string name="喜洋洋";

}

5.测试

public class testor {

@test

public void test(){

applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml");

student stu = (student) context.getbean("stu");

system.out.println(stu.name);

}

}

ioc注入

1.可以不用提供set方法,可以直接在属性名上添加一个@values(值);

import org.springframework.beans.factory.annotation.value;

import org.springframework.stereotype.controller;

@controller("stu2")

public class student {

@value("灰太狼")

private string name;

public string getname() {

return name;

}

}

这样也可以吧值注入进去.

2.有set方法可以直接在set方法上面加上@values(值)也可以吧值注入进去

@controller("stu2")

public class student {

private string name;

public string getname() {

return name;

}

@value("灰太狼")

public void setname(string name) {

this.name = name;

}

}

注解和xml对比

xml可以适用于任何场景,结构清晰。

注解不是自己提供的类,存在局限性;好处:开发简单,方便

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值