码迷,mamicode.com
首页 > 其他好文 > 详细

@Autowired

时间:2016-08-06 09:42:54      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

bean工厂

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    
    <!-- here1 -->
    <context:annotation-config />
    
    <beans>
        <bean id="person" class="cn.zno.hello.Person" >
            <property name="name" value="XiaoMing"></property>
            <property name="age" value="22"></property>
            <property name="savings" value="10000"></property>
        </bean>
        
        <bean id="car" class="cn.zno.hello.Car">
            <property name="brand" value="BYD"></property>
            <property name="price" value="54000"></property>
        </bean>
    </beans>

</beans>

 

测试主函数

    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");

        Person person = (Person) ctx.getBean("person");//here2
        // Person person = new Person(); //here3
        System.out.println(person);
    }

 

javebean 片段

public class Person {
    
    private String name;
    
    private int age;
    
    private double savings;
    
    @Autowired
    private Car car;
    
    
    public void say(){
        System.out.println("Hello World!");
    }
    
    ...

 

 

说明:

here1 开启自动注入

here3 通过 new 的方式无法自动注入

here2 从bean工厂取的bean可以自动注入

 

@Autowired

标签:

原文地址:http://www.cnblogs.com/zno2/p/4767557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!