1. 注解
(1)配置注解
@Config
(2)bean注解
- @Bean注解主要用于方法中,将该方法所返回的对象设置为Bean中。
- @Component 将所注解的类解析成Bean对象,注意调用的是该类的默认构造器。
- @Server,@Controller等注解效果其实都是一样的,只不过为了区分不同的层级进行了逻辑上的区分。
- @Value注解 主要为属性注入值(属性上)。
- @Autowired 既可用于自动装配属性,也可以指定构造对象。 例如:
@Component(value = "construct")
public class MyConstruct {
private Car car;
private Tea tea;
@Autowired
public MyConstruct(Car car,Tea tea){
this.car = car;
this.tea = tea;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Tea getTea() {
return tea;
}
public void setTea(Tea tea) {
this.tea = tea;
}
}
@Configuration
@ComponentScan(basePackages = "spring.consturct")
public class Config {
}
public class MyConstructTest {
public static void main(String[] args) {
}
@Test
public void testConstruct(){
ApplicationContext app = new AnnotationConfigApplicationContext(spring.consturct.Config.class);
MyConstruct myConstruct = (MyConstruct) app.getBean("construct");
System.out.println(myConstruct.getCar().getName());
}
}
运行结果如下: