1、Bean的理解
1、Java面向对象,对象有方法和属性,那么就需要对象实例来调用方法和属性(即实例化);
2、凡是有方法或属性的类都需要实例化,这样才能具象化去使用这些方法和属性;
3、规律:凡是子类及带有方法或属性的类都要加上注册Bean到Spring IoC的注解;
2、Bean的使用
@Bean和@configuration搭配使用
3、用于什么地方
@Bean用于标记在方法上,获取到类的对象。
4、代码的实现
1、创建对象的类
class f{
public void tes1(){
System.out.println("tes1");
}
public String tes11(String name){
return name;
}
}
2、创建bean
@Configuration
class e{
@Bean(name = "my")
public f myf(){
return new f();
}
}
3、创建使用类
public class d {
@Test
public void test1(){
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(e.class);
f g = (f) context.getBean("my");
g.tes1();
System.out.println(g.tes11("龙"));
}
}
打印: