那spring是怎么来管理的呢,首先它会读取在包pakegeZhuJie
下面的所有类,把需要交给spring容器管理的类纳入spring容器中,那么纳入spring容器中的名称又是什么样的呢,spring里面有一个默认的规则,如果没有给定名称,那么bean的名称就是类的简单名称,简单名称就是类的把类的名称第一个字母变成小写。
@Service用于标注业务层组件,@Controler用于标注控制层组件(如structs中的action),@Repositary用于标注数据访问层组件,即DAO组件,而@Conpoment泛指组件,当组件不好归类的时候用这个注释进行标注。
之前我们用的方式是在xml里面配置bean来告诉spring哪些类需要交给spring管理,而这里呢,首先是扫描我们指定的包里面的这些类,如果这些类里面有这些标注的话,spring就知道,这些类需要交给spring管理。
1.新建一个包,包下放需要管理的类,使用这种需要注意自动扫包的类上要加注解才能扫进来。
2.
<?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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
//xml文件中配置好后自动回扫描该包下的所有类(当然可以用过滤只扫描一部分)
<context:component-scan base-package="pakegeZhuJie">
</context:component-scan>
</beans>
3.package pakegeZhuJie;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service
public class PersonServiceBean{
public void Save() {
System.out.println("我怕不会哦");
}
}
4.
package pakegeZhuJie;
import org.springframework.stereotype.Repository;
@Repository
public class ZhuJietest1{
public void add(){
System.out.println("执行PersonDaoBean中的add()方法");
}
}
5.
package pakegeZhuJie;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring(){
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ZhuJietest1 personService = (ZhuJietest1)ctx.getBean("zhuJietest1");
PersonServiceBean test=(PersonServiceBean)ctx.getBean("personServiceBean");
personService.add();
test.Save();
ctx.close();
}
}