Read a configuration file in Java

app.config

app.name=Properties Sample Code
app.version=1.09
Properties prop = new Properties();
String fileName = "app.config";
try (FileInputStream fis = new FileInputStream(fileName)) {
    prop.load(fis);
} catch (FileNotFoundException ex) {
    ... // FileNotFoundException catch is optional and can be collapsed
} catch (IOException ex) {
    ...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));

References
https://stackoverflow.com/questions/16273174/how-to-read-a-configuration-file-in-java

Logging in Spring Boot

When using starters, Logback is used for logging by default.

@RestController
public class LoggingController {

    Logger logger = LoggerFactory.getLogger(LoggingController.class);

    @RequestMapping("/")
    public String index() {
        logger.trace("A TRACE Message");
        logger.debug("A DEBUG Message");
        logger.info("An INFO Message");
        logger.warn("A WARN Message");
        logger.error("An ERROR Message");

        return "Howdy! Check out the Logs to see the output...";
    }
}

the default logging level of the Logger is preset to INFO, meaning that TRACE and DEBUG messages are not visible.

References
https://www.baeldung.com/spring-boot-logging

Controlling Bean Creation Order with @DependsOn Annotation in Spring Boot

Spring, by default, manages beans’ lifecycle and arranges their initialization order.

But, we can still customize it based on our needs. We can choose either the SmartLifeCycle interface or the @DependsOn annotation for managing initialization order.

@Configuration
@ComponentScan("com.baeldung.dependson")
public class Config {
 
    @Bean
    @DependsOn({"fileReader","fileWriter"})
    public FileProcessor fileProcessor(){
        return new FileProcessor();
    }
    
    @Bean("fileReader")
    public FileReader fileReader() {
        return new FileReader();
    }
    
    @Bean("fileWriter")
    public FileWriter fileWriter() {
        return new FileWriter();
    }   
}

Finally, there are few points which we should take care of while using @DependsOn annotation:

  • While using @DependsOn, we must use component-scanning
  • If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored

DependsOnDatabaseInitialization Annotation

Indicate that a bean’s creation and initialization depends upon database initialization having completed. May be used on a bean’s class or its @Bean definition.

References
https://www.baeldung.com/spring-depends-on

Create Events for React Component

Counter.tsx

import {useState} from "react";

function Counter(props: CounterProp) {
    const [count, setCount] = useState(0)

    const buttonClicked = () => {
        setCount(prevState => {

            var result = prevState + 1;

            if (props.onCounterChanged != null) {
                props.onCounterChanged(result);
            }

            return result;
        })
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={buttonClicked}>Next
            </button>
        </div>
    );
}

export interface CounterProp {
    onCounterChanged?: (value: number) => void;
}

export default Counter;

App.tsx

import React from 'react';
import Counter from "./components/Counter";

function App() {
    return (
        <div className={"px-1"}>
            <Counter onCounterChanged={(value => console.log(value))}></Counter>
        </div>

    );
}

export default App;

References
https://www.tutorialsteacher.com/typescript/typescript-interface
https://stackoverflow.com/questions/39713349/make-all-properties-within-a-typescript-interface-optional

Handling Events on React

import {useState} from "react";

function Counter() {
    const [count, setCount] = useState(0)

    const buttonClicked = () => {
        setCount(prevState => prevState + 1)
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={buttonClicked}>Next
            </button>
        </div>
    );
}

export default Counter;

Passing Arguments to Event Handlers

import {useState} from "react";

function Counter() {
    const [count, setCount] = useState(0)

    const buttonClicked = (e: React.MouseEvent<HTMLButtonElement>) => {
        console.log(e);
        setCount(prevState => prevState + 1)
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={(e) => buttonClicked(e)}>Next
            </button>
        </div>
    );
}

export default Counter;

Prevent default behavior

import {useState} from "react";

function Counter() {
    const [count, setCount] = useState(0)

    const buttonClicked = (e: React.MouseEvent<HTMLButtonElement>) => {
        if (e.cancelable)
        {
            e.preventDefault();
        }

        setCount(prevState => prevState + 1)
    };

    return (
        <div>
            <div>Counter Value : {count}</div>
            <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                    onClick={(e) => buttonClicked(e)}>Next
            </button>
        </div>
    );
}

export default Counter;

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

  • Clicking on a “Submit” button, prevent it from submitting a form
  • Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

References
https://reactjs.org/docs/handling-events.html
https://www.w3schools.com/jsref/event_preventdefault.asp
https://stackoverflow.com/questions/32298064/preventdefault-not-working-in-on-input-function

Pass Children Elements in React using children prop

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}    </div>
  );
}

This lets other components pass arbitrary children to them by nesting the JSX:

function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">        Welcome      </h1>      <p className="Dialog-message">        Thank you for visiting our spacecraft!      </p>    </FancyBorder>
  );
}

References
https://reactjs.org/docs/composition-vs-inheritance.html
https://reactjs.org/docs/react-api.html#reactchildren

Using the State Hook to Save Component State in React

useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

useState() should only be used inside a functional component.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  
const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Equivalent Class Example

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

References
https://reactjs.org/docs/hooks-state.html