khateeb
khateeb

Reputation: 5469

The annotation @Bean is disallowed for this location error

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;
    }
}

Upvotes: 3

Views: 21901

Answers (2)

Hrishikesh
Hrishikesh

Reputation: 2053

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.

Upvotes: 8

Haim Raman
Haim Raman

Reputation: 12023

The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

So you need a UserBeanConfig class that will be annotated using @Configuration that will have a method that create the new bean.

@Configuration
public class UserBeanConfig {

   @Bean 
   public UserBean userBean(){
      return new UserBean();
   }
}

From my point of view Spring is not designed to construct simple Domain object. You should use Spring to bootstrap the dependencies of Service/DAO etc.

So I suggest avoiding spring for domain objects.

Upvotes: 3

Related Questions