java - 如何为班级编写@Bean?
问题描述
以下是我的员工班。如果我在第 1 行、第 2 行或第 3 行写入 @Bean 注释,则会引发错误。
它只允许 @Bean 注释到方法名称。为什么?
import org.springframework.context.annotation.Bean;
//line 1
public class Employee {
int id;
String name;
// line 2
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
//line 3
public Employee() {
}
@Bean
public void showCurrentEmployee() {
System.out.println(this.id + " " + this.name);
}
}
正如春天世界所说;Bean 范围是一个单例。这适用于哪里?@Bean 方法如何保存单例实例以及什么?
如果不能将@Bean 赋予类名,那么以下内容如何有效?
<bean name="emp" class="com.myProj.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>John</value>
</property>
</bean>
解决方案
@Bean 注解只能在 Spring 配置类中使用。此类应使用 @Configuration 注释进行注释
通过属性注入,@Value 注释可能会有所帮助。
@Configuration
public class ConfigClass {
@Bean
public BeanClassOne beanOne(@Value("20") Integer intValue) {
return new BeanClassOne(intValue);
}
@Bean
public BeanClassTwo beanTwo() {
return new BeanClassTwo();
}
@Bean
public BeanClassThree beanThree() {
return new BeanClassThree();
}
}
另一种从类中制作 Spring bean 以使用 @Service 或 @Component 注释对其进行注释的方法
@Service
public class BeanClass {
@Value("String value")
privat String strField;
// your bean methods
}
更多信息在这里 https://www.tutorialspoint.com/spring/spring_java_based_configuration.htm
推荐阅读
- wordpress - 我如何让 wp 画廊添加我的图像替代文本
- javascript - 复选框和新组件,工作不规律
- flutter - Flutter TextField 值在 ios 设备上始终为空?
- macos - Chrome 84 - 查找扩展文件夹
- python - Python Thread() 删除换行符?
- fortran - 将分配的数组从子程序传递到 fortran 中的主程序;使用还是模块?界面?
- c# - 如何通过 C# (Unity) 中的代码隐藏画布
- react-native - 组件渲染时 i18n 未初始化
- node.js - 如何部署 Heroku 应用程序并忽略文件?
- python - 以参数作为数据帧的多处理