当前位置: 移动技术网 > IT编程>开发语言>Java > Spring-使用注解开发(十二)

Spring-使用注解开发(十二)

2019年08月06日  | 移动技术网IT编程  | 我要评论

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.配置扫描组件

     <!--自动扫描包下的注解-->
    <context:component-scan base-package="org.west.pojo"/>

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可以适用于任何场景,结构清晰。

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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网