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

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

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

    扫描二维码关注公众号,回复: 6966724 查看本文章

猜你喜欢

转载自www.cnblogs.com/xiaoqiqistudy/p/11312040.html