您的位置:首页 > 编程语言 > Java开发

SpringIOC_容器的类扫描注解

2015-11-02 20:06 429 查看
既然SpingDI(依赖注入)可以使用注解,

那么IOC(把类放到Spring容器中)可以使用吗?在Spring中不写bean

前提:

applicationContext.xml中加入命名空间,添加

<context:component-scan base-package="com.spring.scan">
</context:component-scan>

component:把一个类放入到Spring容器中,该类就是component

在base-package指定的包及子包下扫描所有的类

原理:
* 1, 启动Spring容器,Spring容器解析配置文件
* 2.当解析到<context:component-scan base-package="com.spring.scan">
</context:component-scan>
就会在上面的指定包及子包中扫描所有的类,看那些类上面有@Component注解

3.如果有该注解,则有如下的规则:
@Component
public class PersonDaoImpl{}

<bean id="personDaoImpl" class="...." /> id的值:把类的第一个字母变成小写,其他字母不变

@Component("personDao")
public class PersonDaoImpl{}

<bean id="personDao" class="..."/>

4.安装@Resource注解的规则进行赋值

@Service 服务层

@Controller 控制层

@Repository 持久层(Dao)

分别是@Component的细化,仅仅是名称改变

例子:

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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 
<!--
component:把一个类放入到Spring容器中,该类就是component
在base-package指定的包及子包下扫描所有的类
-->

<context:component-scan base-package="com.spring.scan">
</context:component-scan>
</beans>


Person

package com.spring.scan;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

@Component("person")
public class Person {

@Resource(name="student")
private Student student;

public Student getStudent() {
return student;
}

}


Student

package com.spring.scan;

import org.springframework.stereotype.Component;

@Component("student")
public class Student {

public void say(){

System.out.println("student");
}

}


测试

package com.spring.scan.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.spring.scan.Person;

/**
* 原理:
*         1, 启动Spring容器,Spring容器解析配置文件
*         2.当解析到<context:component-scan base-package="com.spring.scan">
</context:component-scan>
就会在上面的指定包及子包中扫描所有的类,看那些类上面有@Component注解

3.如果有该注解,则有如下的规则:
@Component
public class PersonDaoImpl{}

<bean id="personDaoImpl" class="...." />  id的值:把类的第一个字母变成小写,其他字母不变

@Component("personDao")
public class PersonDaoImpl{}

<bean id="personDao" class="..."/>

4.安装@Resource注解的规则进行赋值

*
*
*
*/
public class ScanTest {

@Test
public void testScan(){

ApplicationContext context=
new ClassPathXmlApplicationContext("applicationContext.xml");

Person person = (Person) context.getBean("person");

person.getStudent().say();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: