• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
终天
博客园    首页    新随笔    联系   管理    订阅  订阅

注解Di及autowire自动注入-浅识

一..注解 全注解 整合

  注解:注解的概念
  注解(Annotation),也叫元数据(MetaData)信息 。一种代码级别的说明。
  它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。
  它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,
  用来对这些元素进行说明,注释

一(1).使用注解DI的步骤

  注解DI的作用:替代xml节点中的所有bean节点

    @Component  标识一个类是被spring容器管理的一个bean

    @Value     给类的普通属性赋值

    @Resource  给类的域属性赋值   JDK提供的注解

    @Autowired  给类的域属性赋值   Spring容器提供的  这个注解不能直接给属性赋值  需要用到@Qualifier(value="student")

一(2).配置步骤:

    1.引入命名空间  context  xmlns:context="http://www.springframework.org/schema/context"


http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 2.在xml节点中写一个包扫描器
<context:component-scan base-package="happy">  全类名
    </context:component-scan>

   3.实体类注解

复制代码
@Component("student")  
public class Student {
    @Value("张三")
    private  String name;
    @Value("20")
    private Integer age;
    @Resource(name="cars")
     private Car car;
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", car=" + car +
                '}';
    }
    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
复制代码

  4.测试类测试代码:

复制代码
   //注解
    @Test
    public void Test06(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext06.xml");
        Student student =(Student) context.getBean("student");
        System.out.println(student);
    }
复制代码

二.autowire自动注入配置

  autowire有了之后,就不需要res来链接bean节点   属性值有byType  byName  

复制代码
   <bean id="cars" class="happy.Car">
    <property name="color" value="蓝色"></property>
    <property name="brand" value="布加迪威龙"></property>
</bean>

    <!--自动配置   设置bean节点的属性为autowire-->
    <bean id="student" class="happy.Student" autowire="byType">
        <property name="name" value="李四"></property>
        <property name="age" value="20"></property>
    </bean>
posted @ 2018-03-08 09:46  一场梦一首歌一个人  阅读(543)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3