@Resource和@Autowired
阿新 • • 發佈:2019-02-17
user.java
package com.pactera.springBean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component("user" )//物件user加入IOC容器,id為user
@Lazy(true)//一旦指定懶載入,註解value預設時true
public class User {
public User(){
System.out.println("建立 user ");
}
private String name="liuqi";
private int age=18;
@Autowired //根據型別去容器中查詢,如果容器中有多個同類型的物件,會丟擲異常 。@Resource有兩個屬性name ,type
//1指定name和type會根據名稱和型別去找唯一的物件2.指定name會去根據id查詢3.指定type會根據型別查詢
//4.都不指定會先根據名稱查詢,沒找到再根據型別查詢,當有多個同類型時會丟擲異常
private String address;
public void setName(String name) {
this.name = name;
}
@PostConstruct //初始化方法
public void initUser(){
System.out.println("init user");
}
@PreDestroy //銷燬容器物件的時候自動呼叫
public void destoryUser(){
System.out.println("destory user");
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}
}
applicationContext.xml
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="address" class="java.lang.String">
<constructor-arg value="上海"></constructor-arg>
</bean>
<!-- <bean id="address2" class="java.lang.String">
<constructor-arg value="上海"></constructor-arg>
</bean> -->
<!-- 掃描包,將配有指定註解的類注入容器 -->
<context:component-scan base-package="com.pactera"></context:component-scan>
</beans>
測試
package com.pactera.springBeanTest;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pactera.springBean.User;
public class TestSpringBean {
@Test
public void testIOC(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = ac.getBean("user", User.class);
System.out.println(user);
ac.destroy();
}
}