spring自动扫描和管理bean

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值