The annotation @Bean is disallowed for this location error

javabeans, spring

Solution

The `@Bean` annotation is to define a Bean to be loaded in the Spring container. it is similar to the xml config of specifying

<bean id="myId" class="..."/>

This should be used in a `Configuration` file(java). Which is similar to your `applicationContext.xml`

@Configuration
@ComponentScan("...")
public class AppConfig{

   @Bean 
   public MyBean  myBean(){
      return new MyBean();
   }
}

The `@Bean, @Configuration` and other newly introduced annotations will do exactly what you do in an Xml config.

Problem

I read in a book that whenever we want a Java-based configuration and want define a bean we use `@Bean` annotation. But when I did that I got the error: `The annotation @Bean is disallowed for this location`. My bean is: ``` package com.mj.cchp.bean; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import org.springframework.context.annotation.Bean; import com.mj.cchp.annotation.Email; @Bean public class UserBean { @NotNull @Email private String email; @NotNull private String firstName; @NotNull private String lastName; @Digits(fraction = 0, integer = 10) private String phoneNo; @NotNull private String role; public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getPhoneNo() { return phoneNo; } public String getRole() { return role; } public void setEmail(String email) { this.email = email; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public void setRole(String role) { this.role = role; } } ```

Original source