Spring 4
阿新 • • 發佈:2020-08-20
就是裝載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();