Anotasi dan Package di Java Spring Boot

In Progress

Autowired

Penjelasan @Autowired dapat disimak di link berikut.

Contoh code dengan @Autowired

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {

    // Tells the application context to inject an instance of UserService here
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

Contoh code tanpa @Autowired

@Controller // Defines that this class is a spring bean
@RequestMapping("/users")
public class SomeController {
    private UserService userService;

    public SomeController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/login")
    public void login(@RequestParam("username") String username,
           @RequestParam("password") String password) {

        // The UserServiceImpl is already injected and you can use it
        userService.login(username, password);

    }
}

Override

Penjelasan @Override dapat disimak pada link berikut.

Contoh code penggunaan @Override pada subclass.

Animal.java
public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}
Dog.java
public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The dog barks");
    }
}

Contoh code penggunaan @Override pada class yang mengimplementasikan method yang sama pada suatu interface.

FooService.java
public interface FooService {
    void doSomething();
}
FooServiceImpl.java
@Service
public class FooServiceImpl implements FooService {
    @Override
    public void doSomething() {
        // ...
    }
}

Qualifier

Penjelasan @Qualifier dapat simak pada link berikut.

Contoh code penggunaan @Qualifier.

FooFormatter.java
@Component("fooFormatter")
public class FooFormatter implements Formatter {
    public String format() {
        return "foo";
    }
}
BarFormatter.java
@Component("barFormatter")
public class BarFormatter implements Formatter {
    public String format() {
        return "bar";
    }
}
FooService.java
@Component
public class FooService {
    @Autowired
    @Qualifier("fooFormatter")
    private Formatter formatter;
}

Package java.util.List

ListExample.java
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("apple");
        list.add("banana");
        list.add("cherry");

        System.out.println(list);
    }
}

Last updated