第一步:实体注释加注入属性
//car实体
解释:注释注入可以没有setter方法,必须有空参,因为IOC容器需要空参构造,不写默认有一个空参
package it.heima.domain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//注释
package it.heima.domain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("car")
public class Car {
@Value("#{'一汽大众'}")
private String name;
@Value("#{10000}")
private Double price;
public Car() {
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
第二步:配置(自动扫描包)
<?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.xsd">
//自动扫描包
<context:component-scan base-package="it.heima.domain"/>
</beans>
第三步:测试
@Test
public void test(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext_annotation.xml");
Car car = applicationContext.getBean("car", Car.class);
System.out.println(car);
}