SpringIOC容器的两种形式:
1.xml配置文件:
applicationContext.xml
2.注解形式:
带有@Configuration注解的类(配置类:相当于applicationContext.xml)
注:两种形式获取的IOC容器是独立的。
IOC容器的功能:
1.存bean
a.xml配置文件形式:
<bean id="" class=""></bean>
b.配置类的形式:
方法上加@Bean注解
2.取bean
a.xml配置文件形式:
//获取IOC容器配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//拿bean对象
Speccontext.getBean("bean对象id值");
b.配置类的形式:
//获取IOC容器配置类
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
//从容器中获取bean对象
Student stu = (Student)context.getBean("myStudent");
配置类的形式存bean:
1.必须有@Configuration注解(配置类)
2.形式:
三层组件:
a.给三层组件分别加注解(@Controller、@Service、@Repository 或可以使用@Component一个注解)
b.将注解所在包 纳入IOC扫描器(ComponentScan)
①使用配置文件applicatonContext.xml添加扫描器:
如:
<context:component-scan base-package="org.neowang.*">
</context:component-scan>
②使用配置类添加扫描器:
在配置类上加注解@ComponentScan(value="要扫描的包名")
非三层组件
a.方法前使用@Bean注解,该bean的id值默认就是方法名(但,可以通过@Bean("id值")来修改)
b. import \ FactoryBean等方式