Spring的IOC注解(Bean)

本文介绍了一个使用Spring框架注解配置的简单示例,通过CustomerService类展示了如何利用@Service、@Scope、@PostConstruct和@PreDestroy等注解来实现Bean的定义及生命周期管理。并通过一个测试类演示了如何通过XML配置文件加载此类并调用其方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CustomerService.java

package com.cherry.spring.demo2;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("customerService")
@Scope
public class CustomerService {

	@PostConstruct//相对与init-method
	public void init() {
		System.out.println("CustomerService被初始化了..");
	}

	public void save() {
		System.out.println("CustomerService的save方式执行..");
	}

	@PreDestroy//相对与destroy-method
	public void destroy() {
		System.out.println("CustomerService被销毁了..");
	}
}

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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Spring的IOC的注解的入门 -->
    <!-- 使用IOC的注解开发,配置扫描(哪些包下的类使用IOC的注解) -->
    <context:component-scan base-package="com.cherry.spring"/>
    
</beans>

测试类

package com.cherry.spring.demo2;

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

public class SpringDemo2 {
	
	@Test
	public void demo1() {
		 ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerService customerService = (CustomerService) applicationContext.getBean("customerService");
		System.out.println(customerService);
		applicationContext.close();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值