首页 > 解决方案 > 如何为班级编写@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> 

标签: javaspringjavabeans

解决方案


@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


推荐阅读