Spring bean管理【基于注解】

本文介绍使用JavaConfig进行Spring Bean的管理方式,包括如何定义Bean、设置作用域及依赖注入等,通过示例代码展示了JavaConfig相较于XML配置的优势。

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

Spring 关于bean的管理有几种方法,常见的有基于注解的javaConfig开发,XML开发,作为一名菜鸟XML开发会更适合,简单易懂,官方文档也写的清楚

不过最近看了Spring in action,学习了利用JavaConfig开发

package Model;

import org.springframework.stereotype.Component;

@Component
public class ClassRoom {
	private Student student;

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	@Override
	public String toString() {
		return "ClassRoom [student=" + student + "]";
	}
	
}

package Model;

import org.springframework.stereotype.Component;

@Component
public class Student {
	private Integer id;
	private String name;
	private Integer age;
	private String major;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getMajor() {
		return major;
	}
	public void setMajor(String major) {
		this.major = major;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + ", major=" + major + "]";
	}
	public void destory(){
		System.out.println("close...");
	}
}

package SpringConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;

import Model.ClassRoom;
import Model.Student;

@Configuration
@ComponentScan(basePackages={"Model"})
@PropertySource("classpath:hello.properties")
@Import(value={javaConfigTo.class})
public class javaConfig {
	
	@Autowired
	Environment evn;
	
	@Bean(destroyMethod="destory",value="student")
	@Scope(scopeName=ConfigurableBeanFactory.SCOPE_SINGLETON)
	public Student returnStudent(){
		Student stu =  new Student();
		stu.setId(1);
		stu.setName(evn.getProperty("root"));//#利用spel表达式可以更强大,直接指定id获取bean
		return stu;
	}
	@Bean("classRoom")
	@Scope(scopeName=ConfigurableBeanFactory.SCOPE_SINGLETON)
	public ClassRoom returnClassRoom(){
		ClassRoom classRoom =  new ClassRoom();
		classRoom.setStudent(returnStudent());
		return classRoom;
	}
}

package SpringConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import Model.Student;

@Configuration
public class javaConfigTo {
	@Bean("student2")
	public Student returnStudent(){
		Student stu = new Student();
		stu.setAge(11);
		return stu;
	}
}
package JunitTest;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import Model.ClassRoom;
import Model.Student;
import SpringConfig.javaConfig;

public class Spring {
	private static ApplicationContext context;
	static{
		context = new AnnotationConfigApplicationContext(javaConfig.class);
	}
	@Test
	public void test() {
		Student student =(Student)context.getBean("student");
//		Student student2 = (Student) context.getBean("student2");
		System.out.println(student);
//		System.out.println(student2);
//		ClassRoom classRoom = (ClassRoom)context.getBean("classRoom");
//		((AnnotationConfigApplicationContext)context).close();
	}
}
@Configuration//配置注解
@ComponentScan(basePackages={"Model"})//扫描组件管理包
@PropertySource("classpath:hello.properties")//设置引入的属性文件,让我们动态注入,非硬编码
@Import(value={javaConfigTo.class})//有点像XML的import,可以分割多分xml配置文件,这里可以结合XML文件也可以多个javaConfig

@Scope(scopeName=ConfigurableBeanFactory.SCOPE_SINGLETON)//作用域

@Autowired
Environment evn;//这个类为我们封装了从引入属性文件获得属性


ps:记一个bean作用域管理的一个小知识点

一般单例模式就可以满足我们的开发,可是如果我们有时候需要基于会话或者请求来获得bean,那么得利用下面的注解


@Scope(value=WebApplicationContext.SCOPE_SESSION,proxyMode=ScopedProxyMode.INTERFACES)


比如购物车的接口,我们希望每个用户都拥有一个属于自己的购物车,所以不能是单例的,但是使用原型又显得过于浪费,性能不高,所以要利用这个注解,他用了代理模式。

当然,如果是类代理的话要使用CGLib代理,就把注解改为

@Scope(value=WebApplicationContext.SCOPE_SESSION,proxyMode=ScopedProxyMode.TARGET_CLASS)


他在对应xml的配置需要引入aop命名空间 <aop:scoped-proxy/> 或者  <aop:scoped-proxy proxy-target-class='false'/ >


Spring中有多种方式来定义和管理bean的生命周期。其中包括使用XML配置、注解和使用JSR250中的@PostConstruct和@PreDestroy注解。 1. XML配置方式:在XML配置文件中,可以使用<bean>标签来定义bean,并通过指定init-method和destroy-method属性来指定bean的初始化和销毁方法。例如: ```xml <bean id="user" class="com.demo.pojo.User" init-method="init" destroy-method="destroy"> </bean> ``` 在这个例子中,init-method属性指定了bean的初始化方法为"init",destroy-method属性指定了bean的销毁方法为"destroy"。 2. 注解方式:使用注解可以更简洁地定义bean的生命周期。可以使用注解@Bean来标注一个方法,该方法返回一个bean实例,并可以使用@PostConstruct和@PreDestroy注解来指定初始化和销毁方法。例如: ```java @Configuration public class AppConfig { @Bean(initMethod = "init", destroyMethod = "destroy") public User user() { return new User(); } } ``` 在这个例子中,@Bean注解标注的方法user()返回一个User实例,并通过initMethod和destroyMethod属性指定了初始化和销毁方法。 3. 使用JSR250中的@PostConstruct和@PreDestroy注解:可以在bean类中使用@PostConstruct和@PreDestroy注解来标注初始化和销毁方法。例如: ```java public class User { @PostConstruct public void init() { // 初始化方法的逻辑 } @PreDestroy public void destroy() { // 销毁方法的逻辑 } } ``` 在这个例子中,@PostConstruct注解标注的方法init()会在bean初始化之后调用,@PreDestroy注解标注的方法destroy()会在bean销毁之前调用。 总结起来,Spring提供了多种方式来定义和管理bean的生命周期,包括XML配置、注解和使用JSR250中的@PostConstruct和@PreDestroy注解。这些方式可以根据具体的需求和项目的特点来选择和使用。[1][2][3]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值