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可以适用于任何场景,结构清晰。
注解不是自己提供的类,存在局限性;好处:开发简单,方便
希望与广大网友互动??
点此进行留言吧!