Close

Spring Framework - @Component Examples

Spring Framework 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MyPrototypeBean {

@Autowired
@Qualifier("basic-service")
private MyService myService;

public void doSomething(){
System.out.println(myService.getMessage());
}
}
Original Post




import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;

@Component
public class MySingletonBean {

@PostConstruct
public void init() {
System.out.println("initializing " +
this.getClass().getSimpleName());
}
}
Original Post




@Lazy
@Service("basic-service")
public class ServiceImplA implements MyService {

@PostConstruct
private void init() {
System.out.println("initializing lazily " +
this.getClass().getSimpleName());
}

@Override
public String getMessage() {
return "Message from " + getClass().getSimpleName();
}
}
Original Post




See Also