1. 通過XML加載Bean (使用傳統的 xml 配置方式創建一個 bean 的方式)
@Test
public void ClassPathXmlApplicationContextTest() {
/**
* 1。xml加載bean
*/
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-main.xml");
LJUserService testService = (LJUserService) ac.getBean("lJUserService");
LJUserQuery query = new LJUserQuery();
List<LJUser> list = testService.selectUserList(query);
System.out.println("getUserId:" + list.get(0).getUserId());
}
2. 利用 @Configuration註解加載Bean(建造者模式的Car見上一篇)
在配置類上加一個 @Configuration 註解,表示聲明該類爲 Spring 的配置類。在創建一個方法,方法返回對象即我們要創建的對象 Car, 返回該對象的實例。在方法上打上註解 @Bean即表示聲明該方法返回的實例是受 Spring 管理的 Bean。
package com.JXWork.test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @auther: TF12778
* @date: 2020/3/21 14:55
* @description:
*/
@Configuration
public class CarConfig {
@Bean
public Car getCar() {
Car car = new Car.Builder().carBody("大衆車身")
.tyre("大衆品牌")
.engine("波音")
.decoration("比亞迪")
.aimingCircle("寶駿")
.safetyBelt("特斯拉")
.build();
return car;
}
}
@Test
public void AnnotationConfigApplicationContextTest() {
/**
* 2。@Configuration 加載bean
*
*/
ApplicationContext ctx = new AnnotationConfigApplicationContext(CarConfig.class);
Car car = ctx.getBean(Car.class);
System.out.println(car);
}