Spring框架复习06-spring注解开发快速入门

第一步:引入jar包(这里是在前面的基础上添加的,就是多引入一个aop的jar包)

 第二步:配置文件引入约束(context约束)

这个约束是注解开发所必须的

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

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       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
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


</beans>

第三步:配置注解包扫描(扫描哪些包下的注解)

<context:component-scan base-package="com.ctbu"/>

第四步:在类上和属性上写上注解

@Component("student")  //相当于是配置文件中配置时 bean中的id属性
public class Student {
    private String name;
    private String age;
    private String sex;

    public String getName() {
        return name;
    }

    @Value("花木兰")  //相当于是配置文件中配置的时候,属性的注入
    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    @Value("23")
    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }
    @Value("女")
    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

第五步:编写测试类

@Test
    public void test2(){

        //加载配置文件
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        //获取配置的对象,通过配置文件中的id
        Student student = (Student) applicationContext.getBean("student");

        System.out.println(student);
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值