spring自动扫描和管理bean

来源:互联网 发布:郑爽白莲花邪教知乎 编辑:程序博客网 时间:2024/04/30 09:53

spring自动扫描和管理bean

写在前面:对于spring我真的是小白,可我这个小白发现spring越来越强大了。今天说一下spring自动扫描和管理bean.

引入spring注解后,有三种方式分别为@service用于注解服务层;@controller用于注解控制层;@responsity用于注解dao;@component用于注解不好分类的类

这几种注解方式目前而言就是一种规范,实际使用效果没有什么区别。

下面讲解spring注解的case.

 

bean.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">  
  <context:component-scan base-package="springdao"/> 
  <context:component-scan base-package="serviceImpl"/> <!--如果包比较多,可以多次引入-->
</beans>

 


 personDao.java

@Controller(value="personDao")  @scope("prototype")
public class personDao {
private String name;
private String dep;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void Test(){
System.out.println("hello,spring");
}
}

 

 

productCreator.java

 

@Component(value="productCreator")
public class productCreator {
@Resource
public personDao pDao=null;
public productCreator(){
System.out.println("........正在被创建!");
}
public static personDao createPersonDao(){
return new personDao();
}
@PostConstruct //初始化方法,在类被实例化的时候就会被执行
public void execPdao(){
pDao.Test();
}
}

 

 

 

springtest.java 

 

public static void main(String[] args) {

ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
personDao pe=(personDao)ctx.getBean("personDao");
productCreator pea=(productCreator)ctx.getBean("productCreator");
pe.Test();
pea.execPdao();
}

 

运行springtest.java得到如下结果:

 

 

........正在被创建!

 

hello,spring
hello,spring

 

原创粉丝点击