在自定义的Java类上加@Configuration注解,表示设定当前类为配置类
package config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
}
(1)在相应的Java类上加@Component注解,表示这是一个bean
package domain;
import org.springframework.stereotype.Component;
@Component
public class Animal {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
注:单独使用@Component注解相当于在xml文件只写了<bean>标签的class属性,@Component(“animal”)相当于在xml文件写了<bean>标签的id和class两个属性
(2)Spring提供了@Component注解的三个衍生注解
在配置类上加@Configuration注解,使其能扫描到定义的bean
@Configuration
@ComponentScan("com.example.domain")
public class SpringConfig {
}
注:@ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个路径需使用数组格式
@ComponentScan({"com.example.service","com.example.domain"})
import config.SpringConfig;
import domain.Animal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Demo {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
Animal animal = ctx.getBean(Animal.class);
System.out.println(animal);
}
}