@Configuration
public class PasswordConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.password.PasswordEncoder;
@SpringBootTest
public class PasswordEncoderTest {
@Autowired
PasswordEncoder passwordEncoder;
@Test
@DisplayName("수동 등록한 passwordEncoder를 주입 받아와 문자열 암호화")
void test1() {
String password = "Robbie's password";
// 암호화
String encodePassword = passwordEncoder.encode(password);
System.out.println("encodePassword = " + encodePassword);
String inputPassword = "Robbie";
// 해시된 비밀번호와 사용자가 입력한 비밀번호를 해싱한 값을 비교
boolean matches = passwordEncoder.matches(inputPassword, encodePassword);
System.out.println("matches = " + matches); // 암호화할 때 사용된 값과 다른 문자열과 비교했기 때문에 false
}
}
1) 같은 타입의 Bean이 여러 개일 경우 - 주입 우선순위
package com.sparta.springauth.food;
public interface Food {
void eat();
}
package com.sparta.springauth.food;
import org.springframework.stereotype.Component;
@Component
public class Chicken implements Food {
@Override
public void eat() {
System.out.println("치킨을 먹습니다.");
}
}
package com.sparta.springauth.food;
import org.springframework.stereotype.Component;
@Component
public class Pizza implements Food {
@Override
public void eat() {
System.out.println("피자를 먹습니다.");
}
}
@SpringBootTest
public class BeanTest {
@Autowired
Food pizza; // ===> 직접 Pizza라고 명시함
@Autowired
Food chicken;
}
@Component
@Primary // ====> 우선순위로 지정하고싶은 빈에 붙인다.
public class Chicken implements Food {
@Override
public void eat() {
System.out.println("치킨을 먹습니다.");
}
}
@SpringBootTest
public class BeanTest {
@Autowired
Food food; // 우선순위를 지정했으므로, food로 써도 된다.
}
@Component
@Qualifier("pizza") // ====> Pizza 클래스에 @Qualifier 추가
public class Pizza implements Food {
@Override
public void eat() {
System.out.println("피자를 먹습니다.");
}
}
@SpringBootTest
public class BeanTest {
@Autowired
@Qualifier("pizza") // ====> 주입하고자 하는 필드에도 똑같이 추가.
Food food;
}
그렇다면, 같은 타입에 Bean에 @Primary와 @Qualifier가 동시에 적용되어 있다면?
따라서, 같은 타입의 Bean이 여러개 있을 때는
참고 : 스프링에서는 주로 좁은 범위의 설정이 더 우선순위가 높다.
| [프로젝트 노트]동시성 이슈를 해결하는 여러가지 방법 (0) | 2024.12.16 |
|---|---|
| TestSuiteExecutionException: Could not execute test class 해결방법 (0) | 2024.12.12 |
| ✍🏻IoC(제어의 역전), DI(의존성 주입) (0) | 2024.12.04 |
| Spring Bean (0) | 2024.12.01 |
| Spring 웹 개발 기본 원리 (0) | 2024.11.30 |