注入String:
<property name=”属性名” value=”xxx”>
注入bean
<property name=”属性名” ref=”xxx”>
注入list
<property name=”属性名” >
<list></list>
<map>
<entry key=”” value=””></entry>
</map>
<props>xxx<prop>
</prop>
</props>
还有 用在外面定义用util
<util:list id=””>就像定义一个bean对象
<util:properties id=””>
表达式注入 就是把现有的对象的属性提取出来在给别的赋值
#{bean对象id.属性} bean一定要有对应的get方法
#{map对象.key} 或者 #{map对象id[‘key’]}(数字定义的key用这个)
#{List对象id[0]}
@Value
注解配置
组件自动扫描 @Component等
要先指定扫描路径:
<context:component-scan base-package=”包的路径”>
对象管理
@Scope
@PostConsruct
@PreDestroy
对象注入
@Resource
@Resource(name=”xxx”)强制按名称来
@Autowired
加上
@Qulifier(‘xxx’)强制按名称来
使用set注入建议用@Resource构造器建议用@Autowired
SpringIOC应用:自己编写的组件建议使用注解配置;框架API只能XML配置
比如写一个bean用作存储连接数据库的信息
那么创建各种属性,给属性赋值的话就是用的注解。先用@Component在类前,好可以扫描进去。然后在属性前用@Value加上表达式来获取配置文件中的值即
@Component
public class MyDataSource {
//经常要变,所以不要写死
//用表达式获取配置文件中的信息。
//注意是 db.key而不是这个属性。
@Value("#{db.username}")
private String username;
@Value("#{db.password}")
private String password;
@Value("#{db.driver}")
private String driver;
@Value("#{db.url}")
private String url;
配置文件中写一个 properties 来存储属性值
<!-- 使用注解的方式注入 将MyDataSource扫描到Spring容器 -->
<context:component-scan base-package="bean.MyDataSource"></context:component-scan>
<!-- 然后利用表达式将db注入到MyDataSource
Spring创建一个Properties对象,然后利用@Value表达式注入将Properties对象信息给MyDataSource注入
-->
<util:properties id="db">
<prop key="username">root</prop>
<prop key="password">123456</prop>
<prop key="driver">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://test</prop>
</util:properties>
因为@Component后面没写那么获取的时候就是默认的即 myDataSource。当然也可以自己定义。
也可以把这些数据库信息存储到一个 mysql.properties文件中。然后在配置文件中设置
<util:proterties id=”db”>
location=”classpath:mysql.properties”
</util:proterties>
来获取。
然后其他的都和之前的方式一致。
IOC:以注入方式应用对象,实现组件解耦