zoukankan      html  css  js  c++  java
  • Spring 4

    就是装载bean三种方法:

      xml装载

      通过注解装配 Bean

      通过隐式 Bean 的发现机制和自动装配的原则

    第一种不经常使用了,我就不讲了

    第二种:通过注解装配 Bean 

    package pojo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component(value = "student1")
    public class Student {
    
        @Value("1")
        int id;
        @Value("student_name_1")
        String name;
    
        // getter and setter
    }

    需要用到@component和@value

    @componnent是用来生成bean对象

    @value是用来装载数据的

    在xml表示

    <bean name="student1" class="pojo.Student">
        <property name="id" value="1" />
        <property name="name" value="student_name_1"/>
    </bean>

    但是现在我们声明了这个类,并不能进行任何的测试,因为 Spring IoC 并不知道这个 Bean 的存在,这个时候我们可以使用一个 StudentConfig 类去告诉 Spring IoC :

    package pojo;
    import org.springframework.context.annotation.ComponentScan;
    
    @ComponentScan
    public class StudentConfig {
    }

    @ComponnentScan是标志

    这个类十分简单,没有任何逻辑,但是需要说明两点:

      • 该类和 Student 类位于同一包名下
      • @ComponentScan注解:
        代表进行扫描,默认是扫描当前包的路径,扫描所有带有 @Component 注解的 POJO。

    然后定义SpringIOC容器的实现类

    ApplicationContext context = new AnnotationConfigApplicationContext(StudentConfig.class);
    Student student = (Student) context.getBean("student1", Student.class);
    student.printInformation();

      

    会当凌绝顶,一览众山小
  • 相关阅读:
    ​特征工程系列:特征预处理(上)
    特征工程系列:特征预处理(下)
    工具使用介绍
    Android图片处理
    Tomcat报java.lang.OutOfMemoryError: Java heap space错误停止运行如何解决
    JBOSS.71.1.Final安装配置
    android:windowSoftInputMode属性详解
    IOS入门之Swift语言(一)
    Android仿微信拍摄短视频
    Android实现播放视频
  • 原文地址:https://www.cnblogs.com/quenvpengyou/p/13538003.html
Copyright © 2011-2022 走看看