-1

I'm working with Spring Boot and I'm having a little trouble understanding Beans. I'm led to believe Beans replace the new keyword.

I identified when using just Autowire my Beans wouldn't create a new instance on an Object and my REST application would return the same response the User first asked for no matter what (i.e. If I visited url/id/1 initially, then visited url/id/2 the REST response would be the same as url/id/1).

I tried to solve this by creating an @Configuration file to define a bean.

@Configuration
public class UserConfig {

    @Autowired
    UserDAO DAO;

    @Bean
    public User getUser(int uid) {
        try {
            return DAO.getUser(uid);
        } catch (SIDException e) {
            return null;
        }
    }
}

But I keep getting this error on runtime: Parameter 0 of method getUser in com.application.Config.UserConfig required a bean of type 'int' that could not be found.

I don't understand this, as I'm trying to define the Bean in the Configuration file.

In my main file I have these annotations:

@SpringBootApplication(scanBasePackages = {"com.application.Config","com.application"})
@ComponentScan({"com.application.Config","com.application"})

And I'm using my bean in this context, if it helps:

@Service
public class UserService {

    @Autowired
    private UserDAO DAO;

    public User getUser(int uid) {
        try {
            return DAO.getUser(uid);
        } catch (SIDException e) {
            return null;
        }
    }
}

Thank you :)

Sarah Macey
  • 196
  • 1
  • 12
  • problem is that because you have a `@Bean` annotation, spring will try to pick that up, expecting that `int` parameter to be a `Bean` also - which you don't have in your context. Looks like simply replacing `@Bean` with `@Service` should work. If that works I could make this an answer - but I don't have an environment at hand to test this... – Eugene Jul 30 '18 at 08:52

2 Answers2

0

The @Bean annotation tells spring to run the methods to instantiate some object. Spring needs to create the argument uid to call your method, but it doesn't know how to instantiate uid. So :

  • Either your int is a constant, so make it static final.
  • Either your int is a configuration, so put it into your application.properties file, and use @Value("${path.to.your.property.key}") to inject it.
Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
0

While Spring tries to create a bean, it needs to know the int uid value. What other answers suggest may resolve the exception.

But what you are trying to do is an improper use of Spring. I recommend you reading up about spring bean eg. this , this before going further.

Your getUser method does not need to be a bean, your dao is bean and that is sufficient. Your UserService looks good, if you get same results for different URL, you should debug the uid value in the UserService.getUser method. If uid is good there then check your query in the Dao.

Rohit
  • 2,132
  • 1
  • 15
  • 24