Spring Framework Methods

Core Spring Framework Methods

Learn about essential Spring Framework methods and their usage in Java applications.

1. BeanFactory Methods

// Get bean by name
Object getBean(String name) throws BeansException;

// Get bean by name and type
 T getBean(String name, Class requiredType) throws BeansException;

// Check if bean exists
boolean containsBean(String name);

// Get bean type
Class getType(String name) throws NoSuchBeanDefinitionException;

// Is bean a singleton/prototype?
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

2. ApplicationContext Methods

// Get environment information
Environment getEnvironment();

// Get application name
String getApplicationName();

// Get startup date
long getStartupDate();

// Publish application event
void publishEvent(ApplicationEvent event);

// Get parent context
ApplicationContext getParent();

3. Bean Lifecycle Methods

@Component
public class ExampleBean implements InitializingBean, DisposableBean {
    
    @PostConstruct
    public void init() {
        // Initialization logic
    }
    
    @Override
    public void afterPropertiesSet() {
        // After properties set
    }
    
    @PreDestroy
    public void cleanup() {
        // Cleanup logic
    }
    
    @Override
    public void destroy() {
        // Destroy logic
    }
}

4. Spring MVC Controller Methods

@RestController
@RequestMapping("/api")
public class ProductController {
    
    @GetMapping("/products")
    public ResponseEntity> getAllProducts() {
        // Return all products
    }
    
    @GetMapping("/products/{id}")
    public ResponseEntity getProductById(@PathVariable Long id) {
        // Return product by ID
    }
    
    @PostMapping("/products")
    public ResponseEntity createProduct(@RequestBody Product product) {
        // Create new product
    }
    
    @PutMapping("/products/{id}")
    public ResponseEntity updateProduct(
            @PathVariable Long id, 
            @RequestBody Product product) {
        // Update existing product
    }
    
    @DeleteMapping("/products/{id}")
    public ResponseEntity deleteProduct(@PathVariable Long id) {
        // Delete product
    }
}

5. Transaction Management

@Service
@Transactional
public class OrderService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Transactional(readOnly = true)
    public Order getOrderById(Long id) {
        return orderRepository.findById(id).orElse(null);
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    public Order createOrder(Order order) {
        // Business logic and save
        return orderRepository.save(order);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void processOrder(Order order) throws Exception {
        // Process order with rollback on any exception
    }
}

6. Spring Data JPA Repository Methods

public interface UserRepository extends JpaRepository {
    
    // Derived query methods
    List findByLastName(String lastName);
    
    // Custom query with @Query
    @Query("SELECT u FROM User u WHERE u.email = ?1")
    User findByEmailAddress(String email);
    
    // Native SQL query
    @Query(value = "SELECT * FROM users WHERE status = 1", nativeQuery = true)
    List findAllActiveUsers();
    
    // Method with pagination
    Page findByLastName(String lastName, Pageable pageable);
    
    // Method with sorting
    List findByLastName(String lastName, Sort sort);
    
    // Custom update query
    @Modifying
    @Query("UPDATE User u SET u.status = :status WHERE u.id = :id")
    int updateUserStatus(@Param("status") int status, @Param("id") Long id);
}

7. Spring Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/login?logout")
                .permitAll();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
            .and()
            .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");
    }
}

8. Spring REST Template

@Service
public class ApiService {
    
    @Autowired
    private RestTemplate restTemplate;
    
    // GET request
    public User getUser(Long id) {
        String url = "https://api.example.com/users/" + id;
        return restTemplate.getForObject(url, User.class);
    }
    
    // POST request
    public User createUser(User user) {
        String url = "https://api.example.com/users";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        HttpEntity request = new HttpEntity<>(user, headers);
        return restTemplate.postForObject(url, request, User.class);
    }
    
    // Exchange method for full control
    public ResponseEntity> getUsers() {
        String url = "https://api.example.com/users";
        return restTemplate.exchange(
            url,
            HttpMethod.GET,
            null,
            new ParameterizedTypeReference>() {}
        );
    }
}

9. Spring AOP (Aspect-Oriented Programming)

@Aspect
@Component
public class LoggingAspect {
    
    // Before advice
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Method called: " + joinPoint.getSignature().getName());
    }
    
    // After returning advice
    @AfterReturning(
        pointcut = "execution(* com.example.service.*.get*(..))",
        returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("Method " + joinPoint.getSignature().getName() + " returned: " + result);
    }
    
    // After throwing advice
    @AfterThrowing(
        pointcut = "execution(* com.example.service.*.*(..))",
        throwing = "error")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
        System.out.println("Exception in " + joinPoint.getSignature().getName() + ": " + error);
    }
    
    // Around advice
    @Around("execution(* com.example.service.*.*(..))")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        try {
            // Proceed with the actual method execution
            Object result = joinPoint.proceed();
            return result;
        } finally {
            long timeTaken = System.currentTimeMillis() - startTime;
            System.out.println("Time taken by " + joinPoint + " is " + timeTaken + "ms");
        }
    }
}

10. Spring Caching

@Service
@CacheConfig(cacheNames = "products")
public class ProductService {
    
    @Autowired
    private ProductRepository productRepository;
    
    @Cacheable
    public Product getProductById(Long id) {
        return productRepository.findById(id).orElse(null);
    }
    
    @CachePut(key = "#product.id")
    public Product updateProduct(Product product) {
        return productRepository.save(product);
    }
    
    @CacheEvict(allEntries = true)
    public void clearCache() {
        // Method to clear all cache entries
    }
    
    @Caching(evict = {
        @CacheEvict(value = "products", key = "#id"),
        @CacheEvict(value = "product-list", allEntries = true)
    })
    public void deleteProduct(Long id) {
        productRepository.deleteById(id);
    }
}

// Configuration
@Configuration
@EnableCaching
public class CacheConfig {
    
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("products", "product-list");
    }
    
    // For production, consider using Redis or EhCache
    // @Bean
    // public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    //     return RedisCacheManager.create(connectionFactory);
    // }
}
Note: Spring Framework provides comprehensive support for enterprise Java applications, including dependency injection, transaction management, web MVC, data access, security, and more.