Spring
1. xml方式注册bean
<bean id="" class="" scope="">
<property name="" value=""/>
<property name="" ref=""/>
</bean>`
解释:
-
id可以替换成name属性,用于标识bean
-
class类路径
-
property和value(ref),表示属性名和值,value用于普通值,ref用于变量(也可以将property换为构造器注入)
-
scope表示bean的范围,默认为单例模式,可以进行设置
-
此方法需要get,set方法支持
2.注解方式注册bean -
首先在Spring的配置文件中开启注解扫描
-
1、配置注解扫描bean进行注册
-
<context:component-scan base-package=“包名”/>
-
2、配置注解扫描注入bean
-
<context:annotation-config/>
-
3.通过@Component进行注入实例,在web衍生的注解方式
-1)dao(@Repository)
-2)service(@Service)
-3)controller(@controller)
bean注解方式注册bean的一种方法
@Component("persion")
public class Persion01 {
@Value("YYY")
String name;
@Value("11")
int age;
}
获取bean的一种方法
@Test
public void test001(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config");
Persion01 persion = applicationContext.getBean("persion", Persion01.class);
System.out.println(persion);
}
3、一个bean中获取另一个bean,注解方式
- 首先在Spring的配置文件中开启注解扫描
- 1、配置注解扫描bean进行注册
- <context:component-scan base-package=“包名”/>
- 2、配置注解扫描注入bean
<context:annotation-config/>
- 3、获取方式
Persion02 的Persion01属性注入了Persion01的bean
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component("persion01")
public class Persion01 {
@Value("YY")
public String name;
@Value("11")
public int age;
}
@Data
@Component("Persion02 ")
public class Persion02 {
@Autowired
Persion01 persion01 ;
}