java自动扫描,Spring_5_组件自动扫描机制

Spring_5_组件自动扫描机制

Web.xml的配置、PersonDao类、PersonDao类与1中相同。

自动扫描机制就是,它可以在类路径下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入Spring容器中管理。

1)PersonDaoBean 类:

@Repository

public class PersonDaoBean implements PersonDao {

public void add() {

System.out.println("执行personDao中的add()方法!");

}

}

2)beans.xml文件的配置:

3)PersonServiceBean 类:

//@Service

// 直接访问PersonServiceBean类

@Service("personService")

// 先访问personService类然后跳转到PersonServiceBean类

@Scope("prototype")

// 每次用PersonServiceBean类都会生成一个新的对象

public class PersonServiceBean implements PersonService {

private PersonDao personDao;

@PostConstruct

// 当实例化PersonServiceBean类时会调init方法

public void init() {

System.out.println("初始化");

}

@PreDestroy

// 当正常关闭资源时回调用destroy方法

public void destroy() {

System.out.println("关闭资源");

}

public void save() {

personDao.add();

}

}

4)springTest 类:

public class springTest {

@Test

public void instanceSpring() {

AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("springXml/beans.xml");

// 使用@Service直接放问PersonServiceBean

// PersonService personServiceBean = (PersonService) ctx.getBean("personService");

// System.out.println(personServiceBean);

// 使用@Service("personService")间接访问PersonServiceBean

// PersonService personService = (PersonService)ctx.getBean("personService");

// System.out.println(personService);

// 在PersonServiceBean类中可以添加@scope("prototype")是每次实例化都生成一个新的对象

// PersonService personService1 = (PersonService)ctx.getBean("personService");

// PersonService personService2 = (PersonService)ctx.getBean("personService");

// System.out.println(personService1 == personService2);

// 在personServiceBean中添加@PostConstruct, 实例化类对象时会调用init()方法

PersonService personServiceBean = (PersonService)ctx.getBean("personService");

System.out.println(personServiceBean);

// 在personServiceBean中添加@PreDestroy,在正常关闭资源时会调用destroy()方法

ctx.close();

}

}

@Service用于标注业务层组件,@Controller用于标注控制层组件(如struts中的action)、@Repository用于标注数据访问组件(DAO组件)、@Component扫描那些不好归类的组件。

http://www.dengb.com/Javabc/863382.htmlwww.dengb.comtruehttp://www.dengb.com/Javabc/863382.htmlTechArticleSpring_5_组件自动扫描机制 Web.xml的配置、PersonDao类、PersonDao类与1中相同。 自动扫描机制就是,它可以在类路径下寻找标注了@Component、@Ser...

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值