本篇主要记录个人学习spring属性注入的几种方法,想要全面了解spring,建议从本系列开头看起。
spring基础篇-入门篇
spring基础篇-Ioc(一)
对象注入
创建两个对象,采用xml注入的方式,调用方法前面已经分享过,这里不做过多介绍。
<bean class="org.zhiqiu.springdemo01.bean.Children" id="children">
<property name="toy" ref="toy"/>
</bean>
<bean class="org.zhiqiu.springdemo01.bean.Toy" id="toy">
<property name="name" value="机器人"/>
<property name="numberNO" value="004"/>
<property name="price" value="144.00"/>
</bean>
数组,集合注入
类
private int age;
private String name;
private Toy toy;
private String[] favorites;
private List<Toy> toys;
//省略getter setter toString方法
<bean class="org.zhiqiu.springdemo01.bean.Children" id="children">
<property name="toy" ref="toy"/>
<property name="favorites">
<list>
<value>音乐</value>
<value>舞蹈</value>
</list>
</property>
<property name="toys" >
<list>
<ref bean="toy"/>
</list>
</property>
</bean>
map Properties注入
类
public class Children {
private Map<Object,Object> map;
private Properties properties;
//省略getter setter toString方法
}
<bean class="org.zhiqiu.springdemo01.bean.Children" id="children">
<property name="map">
<map>
<entry key="name" value="狗蛋"/>
</map>
</property>
<property name="properties">
<props>
<prop key="age">99</prop>
</props>
</property>
</bean>
除了上述xml配置之外,还有java配置。
定义配置文件
@Configuration
public class JavaConfig {
@Bean
Children children(){
return new Children();
}
}
注意 bean的名称默认为注入类的名称
加载调用方法
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
Children children = context.getBean(Children.class);
System.out.println(children.toString());
}
自动化配置
我们常用的,就是第三种,自动化配置,可以再xml中配置,也可以在java代码中配置。
第一步,加入service注解
@Service
public class ToolService {
}
第二步,配置包扫描,注意,如果不配置包扫描,即使有注解,依旧无法将类注册到spring容器中。
@Configuration
@ComponentScan
public class JavaConfig {
@Bean
Children children(){
return new Children();
}
}
这里需要注意的一点是,开启包扫描,默认只扫描当前配置类所在的包下的子包的类。
xml配置
<context:component-scan base-package="org.zhiqiu.springdemo01"/>