Autowired是按照類型注入的(byType)
@Component->通用組件
@Controller->控制器
@Service-> Service
@Repository -> DAO
applicationContext中加入:
```
<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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
<context:component-scan base-package="com.neuedu.test.anotation"></context:component-scan>
```
java類的實現,
```
@Lazy
@Service
public class TestService {
@Autowired
@Qualifier("testSubDAO1")
private TestDAO testDAO;
public void test()
{
System.out.println(testDAO);
}
}
```
```
public class TestDAO {
public void test()
{
System.out.println("testDAO");
}
}
```
```
@Repository
public class TestSubDAO1 extends TestDAO{
public void test()
{
System.out.println("testSubDAO1");
}
}
```
```
@Repository
public class TestSubDAO2 extends TestDAO{
public void test()
{
System.out.println("testSubDAO2");
}
}
```
測試類的實現
```
@Test
public void testIOC4()
{
//1. 啟動spring ioc的容器(BeanFactory, ApplicationContext)
//BeanFactory盡量晚的實例化對象,等到getBean()的時候再實例化。
//applicationContext:盡量早的實例化對象,啟動的時候,把單例的類都實例化好。非單例的類,等到第一次調用getBean實例化
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.
TestService t = (TestService)ctx.getBean("testService");
t.test();
}
```