方式一:
xml配置文件:applicationContext.xml
存bean:<bean id class>
取bean:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean();
方式二:
存bean:
@Bean+方法返回值
@Configuration
public class Test {
//默认名字是stu(方法名),可以自定义(stuBean)
@Bean(stuBean) //@Bean
public Student stu(){
Student stu1 = new Student("zansan", 10);
return stu1; //返回值
}
}
取bean:
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
注解形式的存bean详解:
1、必须有@Configuration注解(配置类)
2、形式:
三层组件(@Controller、@Service、@Repository------>@Component)
整体基础:在三层类上加注解和扫描器,让ioc容器识别
1)给三层组件分别加注解
2)将注解所在包纳入ioc扫描器(ComponentScan):
xml配置文件:
<context:component-scan base-package="com.yanqun.controller"></context:component-scan>
注解扫描器:
component-scan:只对三层负责