1.使用xml文件管理
xml文件内添加bean
<bean id="user" class="com.jt.demo.User"></bean>
调用
顶级容器对象ApplicationContext context =
接收子类new ClassPathXmlApplicationContext("配置文件名称.xml")
context.getBean(类名.class)生成对象 / (强转为对应对象类型)context.getBean("bean id");
2.使用注解管理
a).使用@Bean管理容器方法
写配置类代替xml文件
配置类添加@Configuration注解
在配置类下写容器方法
容器方法添加@Bean注解
return new 需要管理的类对象();//或者反射对象
b).使用@Component管理容器类
写配置类代替xml文件
配置类添加@Configuration注解
配置类添加@ComponentScan("扫描路径")注解
在需要容器管理的类上加@Component注解
调用
顶级容器对象ApplicationContext context =
接收子类new AnnotationConfigApplicationContext("配置类名.class")
context.getBean(类名.class)生成对象 / (强转为对应对象类型)context.getBean("bean id");