SpringBenFactory类
package cn.tedu.spring;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import java.util.Random;
@Configurable
public class SpringBeanFactory {
@Bean
public Random random(){
return new Random();
}
}
SpringRunner类
package cn.tedu.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Random;
public class SpringRunner {
public static void main(String[] args) {
//1.加载spring (可以敲大写ACAC筛选出来)
AnnotationConfigApplicationContext ac
=new AnnotationConfigApplicationContext(SpringBeanFactory.class);
//2.从spring中获取对象 getBean跟SpringBeanFactory类的@Bean注解对应
Random random= (Random) ac.getBean("random");
//3.测试使用对象
System.out.println("random>"+random);
System.out.println("random>"+random.nextInt(100));
//4.关闭
ac.close();
}
}
@Bean :SpringBenFactory类中必须添加@Bean注解,作用是Spring框架自动调用此方法,并管理此方法返回的结果.
@Configurable:在此代码中此注解可以不添加。
- `@Component`:通用组件注解
- `@Controller`:应该添加在“控制器类”上
- `@Service`:应该添加在“业务类”上
- `@Repository`:应该添加在“数据存取类”上
- 另外,`@Configuration`是一种特殊的组件,应该添加在“配置类”上,当执行组件扫描时,添加了`@Configuration`注解的类也会被创建对象
其它:
- 可以在`@Component`等组件注解(不包含`@Configuration`)中配置字符串参数,以显式的指定Bean的名称