@Value注解和@Autowired与@Resource类似,也可以用来注入内容,只不过用法有区别:
1)@Value主要用来注入基本类型的值(包含String),一班不用来注入引用类型
2)只有@Value可以使用Spring表达式
3)@Value也可以使用在setter上
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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="org.spring.teach"/>
</beans>
@Component
public class Phone {
private String num = "123456789";
public String getNum() {
return num;
}
}
@Component
public class User {
//注入引用类型必须使用spring表达式
@Value("#{phone}")
private Phone phone;
//注入bean的属性,是调用该bean的get方法获取的
@Value("#{phone.num}")
private String num;
@Value("zhangsan")
private String name;
@Override
public String toString() {
return "User{" +
"phone=" + phone +
", num='" + num + '\'' +
", name='" + name + '\'' +
'}';
}
}