这个是我从雷锋阳老师的视频那边看的spring源码教程,如果有兴趣可以搜索学一学。
@Autowired中的另外几种用法为:
* @Autowired 构造器,参数,方法,属性;都是从容器中获取参数组件的值
- 标注在方法位置:@Bean+参数:参数从容器中获取;默认不写@Autowired,都能自动转配
- 标在构造器上,如果组件中只有一个有参构造器,那么@Autowired可以省略,参数位置的组件还是可以自动从容器中取
- 放在参数位置
以下是代码示例:
1、vo类
package com.imooc.lamelbdatest.lambdatest.vo;
import org.springframework.stereotype.Component;
/**
* 默认在IOC容器中的组件,容器启动会调用无参构造器创建对象,再进行初始化赋值等操作,
*/
@Component
public class Car {
private String name;
private Integer size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
}
package com.imooc.lamelbdatest.lambdatest.vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 默认在IOC容器中的组件,容器启动会调用无参构造器创建对象,再进行初始化赋值等操作,
*/
@Component
public class Boss {
private Car car;
/**
* 构造器要用的组件,都是从容器中获取
* @param car
*/
@Autowired
public Boss(Car car) {
this.car = car;
System.out.println("boss=========有参构造器");
}
public Car getCar() {
return car;
}
/**
* Autowired 方法标注在方法上,Spring容器创建当前对象,就会调用方法,完成赋值
* 方法使用的参数,自定义类型的值从IOC容器中获取
* @param car
*/
// @Autowired
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Boss{" +
"car=" + car +
'}';
}
}
package com.imooc.lamelbdatest.lambdatest.vo;
public class Color {
private Car car;
@Override
public String toString() {
return "Color{" +
"car=" + car +
'}';
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
2、config类
package com.imooc.lamelbdatest.lambdatest.config;
import com.imooc.lamelbdatest.lambdatest.vo.Car;
import com.imooc.lamelbdatest.lambdatest.vo.Color;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan({"com.imooc.lamelbdatest.lambdatest.vo"})
public class MainConfig {
/**
* @Bean 标注的方法创建对象的时候,方法参数值从容器中获取
* @param car
* @return
*/
@Bean
public Color color(Car car) {
Color color = new Color();
color.setCar(car);
return color;
}
}
3、test类
package com.imooc.lamelbdatest.lambdatest;
/**
* 其他的@Autowired使用
* @Autowired 构造器,参数,方法,属性;都是从容器中获取参数组件的值
* 1)、标注在方法位置:@Bean+参数:参数从容器中获取;默认不写@Autowired,都能自动转配
* 2)、标在构造器上,如果组件中只有一个有参构造器,那么@Autowired可以省略,参数位置的组件还是可以自动从容器中获取
* 3)、放在参数位置
*
*/
public class AutowiredTest {
@Test
public void test1() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Boss bean = applicationContext.getBean(Boss.class);
System.out.println("=========boss is:"+bean);
Car car = applicationContext.getBean(Car.class);
System.out.println("=========Car is:"+car);
Color color = applicationContext.getBean(Color.class);
System.out.println(color);
}
}