Skip to main content
Innovation|Innovation

Spring Boot ఎసెన్షియల్స్: జావా అప్లికేషన్లు ఎలా ప్రాణం పోసుకుంటాయి

Spring Boot fundamentals కి beginner-friendly గైడ్ — application lifecycle, IoC container, dependency injection, annotations cheat sheet, N-Tier architecture, Records తో DTOs, global exception handling, మరియు @Valid తో validation.

8 ఏప్రిల్, 202612 min read

Spring Boot అంటే ఏమిటి మరియు మీకు ఎందుకు అవసరం?

మీరు ఒక ఇల్లు కట్టాలనుకుంటున్నారని ఊహించుకోండి. మీరు ప్రతి ఇటుక, వైర్, పైపు విడిగా కొనుగోలు చేసి, అవి ఎలా కనెక్ట్ అవుతాయో తెలుసుకుని, కేవలం ప్లంబింగ్ కోసమే నెలల తరబడి గడపవచ్చు. లేదా ఒక బిల్డర్‌ను హైర్ చేయవచ్చు — అతనికి blueprint తెలుసు, materials సిద్ధంగా ఉన్నాయి, పూర్తయిన ఇల్లు మీకు అందిస్తాడు — మీరు కేవలం paint color ఎంచుకోండి.

Spring Boot జావా డెవలపర్ల కోసం అదే చేస్తుంది. Plain Java మీకు ఇటుకలు ఇస్తుంది. Spring Framework blueprint ఇస్తుంది. Spring Boot లైట్లు ఆన్ చేసిన పూర్తయిన ఇల్లు ఇస్తుంది.

ఈ గైడ్‌లో, Spring Boot application ఎలా start అవుతుందో, మీ objects ను ఎలా manage చేస్తుందో, మీ code ను clean layers గా ఎలా organize చేయాలో, మరియు errors మరియు validation ను ఎలా handle చేయాలో — అన్నీ practical code examples తో నేర్చుకుంటారు.

Application Lifecycle: main() నుండి Ready వరకు

ప్రతి Spring Boot application ఒక single class తో మొదలవుతుంది. కంప్యూటర్‌లో power button నొక్కినట్లు ఆలోచించండి — ఒక్క click, మరియు వెనుక అనేక విషయాలు జరుగుతాయి.

@SpringBootApplication — అన్నింటినీ నియంత్రించే ఒకే Annotation

@SpringBootApplication నిజానికి మూడు annotations ను ఒకటిగా కలిపింది:

  • @SpringBootConfiguration — ఈ class ను configuration source గా గుర్తిస్తుంది (settings file లాగా)
  • @EnableAutoConfiguration — మీ దగ్గర ఏ libraries ఉన్నాయో చూసి Spring Boot ను automatically configure చేయమని చెబుతుంది
  • @ComponentScan — ఈ package మరియు దాని కింద special annotations ఉన్న classes కోసం search చేయమని Spring కి చెబుతుంది
@SpringBootApplication
public class BookStoreApplication {
    public static void main(String[] args) {
        SpringApplication.run(BookStoreApplication.class, args);
    }
}

మీరు దీన్ని run చేసినప్పుడు, Spring Boot ఈ క్రమంలో చేస్తుంది:

  1. ApplicationContext ను సృష్టిస్తుంది — మీ అన్ని objects ను ("beans" అని పిలుస్తారు) hold చేసే container
  2. Components కోసం scan చేస్తుంది@Service, @Repository, @Controller మొదలైనవి ఉన్న ప్రతి class ను కనుగొంటుంది
  3. Auto-configure చేస్తుంది — database driver ఉందా? Connection pool set up చేస్తుంది. Web dependency ఉందా? Embedded Tomcat server start చేస్తుంది.
  4. Startup hooks ను run చేస్తుంది — ఏదైనా CommandLineRunner లేదా ApplicationRunner beans ను execute చేస్తుంది
  5. Ready — మీ app live గా requests కోసం listen చేస్తోంది
// Startup లో ఏదైనా run చేయాలా? CommandLineRunner ఉపయోగించండి
@Component
public class DataLoader implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("Application started! Loading initial data...");
    }
}

IoC Container: Spring ను మీ కోసం వంట చేయనివ్వండి

IoC అంటే Inversion of Control. ఇక్కడ సరళమైన analogy ఉంది:

IoC లేకుండా (ఇంట్లో వంట చేయడం): మీరు దుకాణానికి వెళ్లి, ingredients కొని, కూరగాయలు తరిగి, స్టవ్ వేడి చేసి, భోజనం వండి, గిన్నెలు కడుగుతారు. మీరు అన్నింటినీ control చేస్తారు.

IoC తో (restaurant లో తినడం): మీరు కూర్చుని, menu నుండి order చేసి, chef మీకు భోజనం తెస్తాడు. భోజనం ఎలా తయారవుతుందో మీరు control చేయరు — restaurant చేస్తుంది. మీరు కేవలం మీకు ఏమి కావాలో చెప్పండి.

Spring Boot లో, IoC Container (ApplicationContext అని కూడా పిలుస్తారు) restaurant లాంటిది. మీ classes dishes. మీకు ఏమి కావాలో describe చేయండి, Spring అన్నింటినీ create, connect మరియు manage చేస్తుంది.

Bean అంటే ఏమిటి?

Bean అనేది Spring create మరియు manage చేసే Java object. మీరు new ProductService() రాయడానికి బదులు, Spring దాన్ని create చేసి, memory లో ఉంచి, అవసరమైన ఎవరికైనా ఇస్తుంది.

// మీరు ఇది రాయరు:
ProductRepository repo = new ProductRepository();
ProductService service = new ProductService(repo);

// SPRING మీ కోసం చేస్తుంది — మీరు కేవలం అడగండి:
@Service
public class ProductService {
    private final ProductRepository repository;

    // Spring ఈ constructor ను చూసి, ProductRepository bean ను కనుగొని,
    // automatically pass చేస్తుంది
    public ProductService(ProductRepository repository) {
        this.repository = repository;
    }
}

Dependency Injection: మీకు కావలసింది అడగడం

Dependency Injection (DI) అనేది IoC యొక్క ఎలా భాగం. మీ class depend అయ్యే objects ను Spring ఎలా ఇస్తుందో అది. Room service లాగా ఆలోచించండి — మీరు front desk కి call చేసి "నాకు towels కావాలి" అని చెబితే, వాళ్ళు మీ door వద్దకు towels తెస్తారు. మీరు laundry room కి వెళ్ళరు.

మూడు రకాల Injection

// 1. CONSTRUCTOR INJECTION (recommended — ఉత్తమ మార్గం)
@Service
public class OrderService {
    private final ProductRepository productRepo;
    private final EmailService emailService;

    // Spring రెండు dependencies ను constructor ద్వారా inject చేస్తుంది
    public OrderService(ProductRepository productRepo, EmailService emailService) {
        this.productRepo = productRepo;
        this.emailService = emailService;
    }
}

// 2. SETTER INJECTION (optional dependencies కోసం)
@Service
public class ReportService {
    private CacheService cacheService;

    @Autowired(required = false)
    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }
}

// 3. FIELD INJECTION (avoid — test చేయడం కష్టం)
@Service
public class NotificationService {
    @Autowired  // పనిచేస్తుంది కానీ recommend చేయబడదు
    private EmailService emailService;
}

Constructor injection ఉత్తమం ఎందుకు:

  • మీ fields final గా ఉంటాయి — ఒకసారి set చేస్తే, ఎప్పుడూ మారవు
  • Test చేయడం సులభం — constructor లో mock objects pass చేయండి
  • Dependency missing అయితే, app startup లోనే fail అవుతుంది (runtime లో user click చేసినప్పుడు కాదు)

Annotations Cheat Sheet: Spring కి ఏమి చేయాలో చెప్పే Labels

Annotations party లో name tags లాంటివి. మీరు class మీద @Service పెట్టినప్పుడు, Spring కి చెబుతున్నారు: "నేను ఒక service ని — దయచేసి నన్ను manage చేయండి." మీకు తెలియవలసిన ప్రతి annotation ఇక్కడ ఉంది:

Component Annotations (Spring వీటి కోసం scan చేస్తుంది)

// @Component — generic "నేను Spring-managed bean ని"
@Component
public class PdfGenerator { }

// @Service — business logic layer (@Component లాగే, కానీ intent clear గా ఉంటుంది)
@Service
public class EmployeeService {
    public Employee findById(Long id) { ... }
}

// @Repository — data access layer (automatic exception translation add చేస్తుంది)
@Repository
public class EmployeeRepository {
    public Employee save(Employee employee) { ... }
}

// @RestController — HTTP requests handle చేసి JSON directly return చేస్తుంది
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @GetMapping("/{id}")
    public Product getProduct(@PathVariable Long id) { ... }
}

// @Controller — HTTP requests handle చేసి HTML views return చేస్తుంది
@Controller
public class HomeController {
    @GetMapping("/")
    public String home(Model model) {
        return "index";  // index.html template ను return చేస్తుంది
    }
}

Configuration Annotations

// @Bean — @Configuration class లో manually bean create చేయడం
@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }
}

// @Value — application.properties నుండి values inject చేయడం
@Service
public class EmailService {
    @Value("${app.email.from:noreply@example.com}")
    private String fromAddress;

    @Value("${app.email.max-retries:3}")
    private int maxRetries;
}

// @Profile — నిర్దిష్ట environments లో మాత్రమే beans activate చేయడం
@Configuration
@Profile("dev")
public class DevConfig {
    @Bean
    public DataSource dataSource() {
        // Development కోసం H2 in-memory database
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2)
            .build();
    }
}

@Configuration
@Profile("prod")
public class ProdConfig {
    @Bean
    public DataSource dataSource() {
        // Production కోసం నిజమైన PostgreSQL
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl("jdbc:postgresql://db-server:5432/myapp");
        return ds;
    }
}

Quick Reference Table

Annotationఉద్దేశ్యంLayer
@ComponentGeneric Spring beanఏదైనా
@ServiceBusiness logicService
@RepositoryData access + exception translationData
@RestControllerREST API endpoints (JSON return చేస్తుంది)Web
@ControllerMVC endpoints (views return చేస్తుంది)Web
@ConfigurationManually beans define చేస్తుందిConfig
@Bean@Configuration లో bean create చేస్తుందిConfig
@ValueProperty values inject చేస్తుందిఏదైనా
@ProfileEnvironment ప్రకారం beans activate చేస్తుందిConfig
@AutowiredDependencies inject చేస్తుంది (constructor prefer చేయండి)ఏదైనా

N-Tier Architecture: బాగా నడిచే వంటగది లాగా Code Organize చేయడం

ప్రొఫెషనల్ kitchen లో stations ఉంటాయి: ఒకరు కూరగాయలు prep చేస్తారు, మరొకరు meat grill చేస్తారు, ఇంకొకరు food plate చేస్తారు. ఎవరూ అన్నీ చేయరు. N-Tier architecture అదే — ప్రతి layer కి ఒకే job ఉంటుంది.

Spring Boot లో, standard setup మూడు layers:

HTTP Request
    |
    v
[Controller Layer]  — Order తీసుకుంటుంది (HTTP requests parse చేస్తుంది)
    |
    v
[Service Layer]     — భోజనం వండుతుంది (business logic)
    |
    v
[Repository Layer]  — pantry నుండి ingredients తెస్తుంది (database access)
    |
    v
[Database]          — pantry (అన్నింటినీ store చేస్తుంది)

పూర్తి ఉదాహరణ: Employee Management

HTTP request నుండి database వరకు మరియు తిరిగి పూర్తి flow build చేద్దాం.

Step 1: Entity — database లో store అయ్యేది

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false, unique = true)
    private String email;

    private String department;

    // constructors, getters, setters
}

Step 2: Repository — database తో మాట్లాడుతుంది

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    // Method name ఆధారంగా Spring మీ కోసం SQL రాస్తుంది!
    List<Employee> findByDepartment(String department);
    Optional<Employee> findByEmail(String email);
    boolean existsByEmail(String email);
}

Step 3: Service — అన్ని business logic ఉంటుంది

@Service
public class EmployeeService {
    private final EmployeeRepository repository;

    public EmployeeService(EmployeeRepository repository) {
        this.repository = repository;
    }

    public List<Employee> getAllEmployees() {
        return repository.findAll();
    }

    public Employee getEmployeeById(Long id) {
        return repository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Employee not found with id: " + id));
    }

    public Employee createEmployee(Employee employee) {
        if (repository.existsByEmail(employee.getEmail())) {
            throw new DuplicateResourceException("Email already exists: " + employee.getEmail());
        }
        return repository.save(employee);
    }

    public Employee updateEmployee(Long id, Employee updated) {
        Employee existing = getEmployeeById(id);
        existing.setName(updated.getName());
        existing.setEmail(updated.getEmail());
        existing.setDepartment(updated.getDepartment());
        return repository.save(existing);
    }

    public void deleteEmployee(Long id) {
        Employee employee = getEmployeeById(id);
        repository.delete(employee);
    }
}

Step 4: Controller — HTTP requests handle చేస్తుంది

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
    private final EmployeeService service;

    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @GetMapping
    public List<Employee> getAll() {
        return service.getAllEmployees();
    }

    @GetMapping("/{id}")
    public Employee getById(@PathVariable Long id) {
        return service.getEmployeeById(id);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Employee create(@Valid @RequestBody Employee employee) {
        return service.createEmployee(employee);
    }

    @PutMapping("/{id}")
    public Employee update(@PathVariable Long id, @Valid @RequestBody Employee employee) {
        return service.updateEmployee(id, employee);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        service.deleteEmployee(id);
    }
}

Java Records తో DTOs: మీ Database ను బయటి ప్రపంచానికి ఎప్పుడూ expose చేయకండి

DTO (Data Transfer Object) restaurant లో menu లాంటిది. Kitchen లో raw chicken, knives మరియు ovens ఉంటాయి — కానీ మీరు అవన్నీ చూడాలనుకోరు. మీరు order చేయగలిగేది మాత్రమే చూపించే clean menu కావాలి.

అలాగే, మీ Entity లో database details (ID generation strategy, column constraints) ఉంటాయి — API users వాటిని చూడకూడదు. DTO వారికి అవసరమైన fields మాత్రమే చూపిస్తుంది.

Java Records (Java 16+) DTOs ను చాలా clean గా చేస్తాయి — getters, setters, equals, hashCode లేదా toString రాయాల్సిన అవసరం లేదు:

// Request DTO — employee create చేయడానికి client పంపేది
public record CreateEmployeeRequest(
    @NotBlank(message = "Name is required")
    String name,

    @Email(message = "Must be a valid email")
    @NotBlank(message = "Email is required")
    String email,

    String department
) {}

// Response DTO — client కి తిరిగి వచ్చేది
public record EmployeeResponse(
    Long id,
    String name,
    String email,
    String department,
    LocalDateTime createdAt
) {
    // Entity -> DTO convert చేయడానికి Static factory method
    public static EmployeeResponse from(Employee entity) {
        return new EmployeeResponse(
            entity.getId(),
            entity.getName(),
            entity.getEmail(),
            entity.getDepartment(),
            entity.getCreatedAt()
        );
    }
}

// Controller లో ఉపయోగం
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public EmployeeResponse create(@Valid @RequestBody CreateEmployeeRequest request) {
    Employee employee = new Employee(request.name(), request.email(), request.department());
    Employee saved = service.createEmployee(employee);
    return EmployeeResponse.from(saved);
}

@GetMapping
public List<EmployeeResponse> getAll() {
    return service.getAllEmployees().stream()
        .map(EmployeeResponse::from)
        .toList();
}

Global Exception Handling: అన్ని Errors కోసం ఒకే చోటు

Global exception handling లేకుండా, ప్రతి controller method కి try-catch blocks అవసరం — messy మరియు repetitive. Spring @RestControllerAdvice ఇస్తుంది, ఇది controller నుండైనా exceptions catch చేసే safety net లాగా పనిచేస్తుంది.

Mall లో customer service desk లాగా ఆలోచించండి. ఏ store లో problem వచ్చినా, మీరు అన్ని complaints handle చేసే ఒక central desk కి వెళ్తారు.

// Step 1: Custom exceptions define చేయండి
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

public class DuplicateResourceException extends RuntimeException {
    public DuplicateResourceException(String message) {
        super(message);
    }
}

// Step 2: Standard error response create చేయండి
public record ErrorResponse(
    int status,
    String error,
    String message,
    LocalDateTime timestamp
) {
    public static ErrorResponse of(HttpStatus status, String message) {
        return new ErrorResponse(
            status.value(),
            status.getReasonPhrase(),
            message,
            LocalDateTime.now()
        );
    }
}

// Step 3: Global exception handler — అన్ని controllers నుండి errors catch చేస్తుంది
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
        return ErrorResponse.of(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(DuplicateResourceException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public ErrorResponse handleDuplicate(DuplicateResourceException ex) {
        return ErrorResponse.of(HttpStatus.CONFLICT, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleValidation(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
            .map(error -> error.getField() + ": " + error.getDefaultMessage())
            .collect(Collectors.joining(", "));
        return ErrorResponse.of(HttpStatus.BAD_REQUEST, message);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleGeneral(Exception ex) {
        return ErrorResponse.of(HttpStatus.INTERNAL_SERVER_ERROR,
            "ఏదో తప్పు జరిగింది. దయచేసి మళ్ళీ ప్రయత్నించండి.");
    }
}

ఇప్పుడు ఏ controller అయినా ResourceNotFoundException throw చేస్తే, client కి ఇలాంటి clean JSON response వస్తుంది:

{
    "status": 404,
    "error": "Not Found",
    "message": "Employee not found with id: 42",
    "timestamp": "2026-04-08T10:30:00"
}

@Valid తో Validation: చెడు Data ను Door వద్దే ఆపండి

Validation అనేది club వద్ద bouncer లాంటిది. ఎవరైనా లోపలికి రాకముందు, bouncer check చేస్తాడు: మీరు list లో ఉన్నారా? మీ దగ్గర ID ఉందా? మీ వయస్సు సరిపోతుందా? ఏ check fail అయినా, మీరు లోపలికి రారు.

Spring Boot incoming data ను automatically check చేయడానికి Jakarta Bean Validation annotations ఉపయోగిస్తుంది:

public record CreateProductRequest(
    @NotBlank(message = "Product name is required")
    @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters")
    String name,

    @NotNull(message = "Price is required")
    @Positive(message = "Price must be greater than zero")
    BigDecimal price,

    @Min(value = 0, message = "Stock cannot be negative")
    int stock,

    @NotBlank(message = "Category is required")
    String category,

    @Size(max = 500, message = "Description cannot exceed 500 characters")
    String description
) {}

// Controller లో, @Valid మీ code run అవ్వడానికి ముందే validation trigger చేస్తుంది
@PostMapping("/api/products")
public ProductResponse create(@Valid @RequestBody CreateProductRequest request) {
    // అన్ని validations pass అయితే మాత్రమే ఈ code run అవుతుంది
    return service.createProduct(request);
}

సాధారణ Validation Annotations

Annotationఏమి Check చేస్తుందిఉదాహరణ
@NotNullNull కాదు (కానీ empty అవ్వవచ్చు)@NotNull Integer age
@NotBlankNull కాదు, empty కాదు, spaces మాత్రమే కాదు@NotBlank String name
@NotEmptyNull కాదు మరియు empty కాదు@NotEmpty List<String> tags
@SizeLength range లో ఉందా@Size(min=2, max=50)
@Min / @MaxNumeric minimum / maximum@Min(0) int quantity
@PositiveZero కంటే ఎక్కువ@Positive BigDecimal price
@EmailValid email format@Email String email
@PatternRegex కి match అవుతుందా@Pattern(regexp="[A-Z]{2}\\d{4}")
@Past / @FutureDate గతంలో / భవిష్యత్తులో ఉందా@Past LocalDate birthDate

Custom Validation — Built-In సరిపోనప్పుడు

// Step 1: Annotation create చేయండి
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NoProfanityValidator.class)
public @interface NoProfanity {
    String message() default "Content contains inappropriate language";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

// Step 2: Validator create చేయండి
public class NoProfanityValidator implements ConstraintValidator<NoProfanity, String> {
    private static final Set<String> BLOCKED_WORDS = Set.of("spam", "scam");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) return true;
        String lower = value.toLowerCase();
        return BLOCKED_WORDS.stream().noneMatch(lower::contains);
    }
}

// Step 3: ఉపయోగించండి
public record CreateReviewRequest(
    @NoProfanity
    @NotBlank
    String comment,

    @Min(1) @Max(5)
    int rating
) {}

అన్నీ కలిపి: పెద్ద చిత్రం

మీ Spring Boot application కి request వచ్చినప్పుడు అన్నీ ఎలా connect అవుతాయో ఇక్కడ ఉంది:

POST /api/employees  (JSON body: {"name": "Alice", "email": "alice@example.com"})
        |
        v
  [@Valid] Validation మొదట run అవుతుంది
        |  (fail అయితే? -> GlobalExceptionHandler 400 Bad Request return చేస్తుంది)
        v
  [EmployeeController] CreateEmployeeRequest DTO receive చేస్తుంది
        |
        v
  [EmployeeService] business rules check చేస్తుంది (email already exists?)
        |  (duplicate? -> DuplicateResourceException throw -> handler 409 Conflict return చేస్తుంది)
        v
  [EmployeeRepository] database లో save చేస్తుంది
        |
        v
  [EmployeeResponse DTO] JSON గా return అవుతుంది
        |
        v
  201 Created  {"id": 1, "name": "Alice", "email": "alice@example.com"}

తరచుగా అడిగే ప్రశ్నలు

@Component, @Service మరియు @Repository మధ్య తేడా ఏమిటి?

Functionally, అవన్నీ ఒకే పని చేస్తాయి — Spring ను bean create మరియు manage చేయమని చెబుతాయి. తేడా intent లో ఉంది. @Component generic label. @Service "ఈ class business logic కలిగి ఉంది" అని చెబుతుంది. @Repository "ఈ class database తో మాట్లాడుతుంది" అని చెబుతుంది మరియు automatic exception translation add చేస్తుంది (database-specific exceptions ను Spring యొక్క DataAccessException గా convert చేస్తుంది). Job titles లాగా ఆలోచించండి: అందరూ employees (@Component), కానీ కొందరు managers (@Service) మరియు కొందరు warehouse workers (@Repository). మీ code చదివే ఎవరైనా class ఏమి చేస్తుందో వెంటనే తెలుసుకునేలా specific label ఉపయోగించండి.

Field injection కంటే constructor injection ఎందుకు recommend చేస్తారు?

మూడు కారణాలు. మొదటిది, మీ dependencies final గా ఉంటాయి, అంటే ఒకసారి set అయిన తర్వాత ఎప్పుడూ మారవు — ఇది multi-threaded environments లో మీ class ను safe గా చేస్తుంది. రెండవది, testing సులభం: Spring context అవసరం లేకుండా constructor లో mock objects pass చేయండి. మూడవది, మీరు dependency మర్చిపోతే, app వెంటనే startup లో clear error message తో fail అవుతుంది, user code path trigger చేసినప్పుడు runtime లో crash అవ్వడానికి బదులు. @Autowired తో field injection మీ dependencies ను hide చేస్తుంది మరియు classes ను test మరియు reason about చేయడం కష్టతరం చేస్తుంది.

@Component బదులు @Bean ఎప్పుడు ఉపయోగించాలి?

మీరు రాసే classes కోసం @Component (లేదా @Service, @Repository) ఉపయోగించండి. మీ source code లేని third-party libraries నుండి objects కోసం @Configuration class లో @Bean ఉపయోగించండి — ఎందుకంటే వాటి source code మీ దగ్గర లేదు కాబట్టి annotate చేయలేరు. ఉదాహరణకు, RestTemplate లేదా ObjectMapper మీద @Component పెట్టలేరు ఎందుకంటే అవి external libraries నుండి వచ్చాయి. బదులుగా, @Bean annotate చేసిన method create చేసి configured instance return చేయండి, Spring దాన్ని అక్కడ నుండి manage చేస్తుంది.

Request మీద validation fail అయితే ఏమి జరుగుతుంది?

మీరు @RequestBody parameter మీద @Valid పెట్టినప్పుడు, Spring మీ controller method run అవ్వడానికి ముందే అన్ని validation annotations (@NotBlank, @Email, @Size, మొదలైనవి) check చేస్తుంది. ఏ check fail అయినా, Spring MethodArgumentNotValidException throw చేస్తుంది. Global exception handler లేకుండా, ఇది messy 400 response return చేస్తుంది. @RestControllerAdvice handler తో (పైన చూపించినట్లుగా), ఈ exception catch చేసి ఏ fields fail అయ్యాయో మరియు ఎందుకో exactly చూపించే clean, user-friendly JSON error return చేయవచ్చు.

ఒకే సమయంలో అనేక profiles active చేయవచ్చా?

అవును. application.properties లో spring.profiles.active=dev,metrics,logging set చేయడం ద్వారా, command-line argument గా (--spring.profiles.active=dev,metrics), లేదా environment variable గా multiple profiles activate చేయవచ్చు. Active profiles లో ఏదైనా match అయ్యే అన్ని beans create అవుతాయి. ఇది concerns mix చేయడానికి useful: dev మీ database కోసం, metrics monitoring కోసం, logging verbose logs కోసం. Production తప్ప ప్రతి profile లో bean activate చేయడానికి @Profile("!prod") కూడా ఉపయోగించవచ్చు.

More from Innovation

Innovation

ఈ ఏడాది తెలివితేటలు చౌకయ్యాయి — విలువ మీరు దానితో నిర్మించేదానికి మారింది

ఒక మిలియన్ AI టోకెన్ల ఖర్చు ఒకే ఏడాదిలో దాదాపు నాలుగు రెట్లు తగ్గింది. ముడిసరుకు ఇంత వేగంగా చౌకైనప్పుడు, ప్రయోజనం మోడల్ ఎవరిది అనేది కాకుండా ఉపయోగకరమైనది ఎవరు నిర్మిస్తారు అనేదిగా మారుతుంది.

14, జూన్ 20263 min read
Innovation

రోబోట్లు ప్రదర్శన ఆపి పని మొదలుపెట్టిన సంవత్సరం

ఒక దశాబ్దం పాటు హ్యూమనాయిడ్ రోబోట్లు కేవలం డెమో వీడియోలే — ఎప్పుడూ ఆకట్టుకునేవి, ఎప్పుడూ ఐదేళ్ళ దూరంలో ఉండేవి. 2026లో కథ నిశ్శబ్దంగా వీడియోల నుండి ఉత్పత్తి సంఖ్యలకు మారింది.

14, జూన్ 20263 min read
Innovation

AI నెలనెలా చౌకవుతోంది. మరి అందరి AI బిల్లులు ఎందుకు పేలిపోతున్నాయి?

AI ధర ఏడాదిలో సుమారు 4 రెట్లు తగ్గింది — కానీ కంపెనీలు వార్షిక AI బడ్జెట్లను నెలల్లో ఖర్చు చేస్తున్నాయి. రెండూ నిజమే — కారణం అర్థం చేసుకోవడం ముఖ్యం.

12, జూన్ 20263 min read