02 autowire注解的使用

2018-05-13  本文已影响0人  hayes0420

@Autowired:该注解应用于有值设值方法、非设值方法、构造方法和变量。

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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">



    <context:component-scan base-package="com.lyc" />

    <bean id="helloWorld" class="com.lyc.spring.HelloWorld">
        <property name="name" value="Spring_HelloWorld"></property>
    </bean>

    <bean id="car" class="com.lyc.spring.Car"></bean>  
    <bean id="user" class="com.lyc.spring.User" autowire="byName"></bean>  


</beans>    

换句话理解是省去了get set的方法,
创建一个car

package com.lyc.spring;

public class Car {
    public void start(){  
        System.out.println("starting car...");  
    } 
}

创建一个User,使用autowire可以省去setcar

package com.lyc.spring;

import org.springframework.beans.factory.annotation.Autowired;

public class User {
    @Autowired  
    private Car car;

//  public void setCar(Car car) {
//      this.car = car;
//  }

    public void startCar() {
        car.start();
    }
}

测试

public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");

        
        User user = (User) ctx.getBean("user");  
        user.startCar(); 

    }

}

如果把autowire去除 报错 Exception in thread "main" java.lang.NullPointerException

上一篇 下一篇

猜你喜欢

热点阅读