spring基础篇-Ioc篇(二)

本篇主要记录个人学习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"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值