[static-injection] improvement

This commit is contained in:
Kai.Yuan 2024-03-30 22:44:48 +01:00
parent 317496fa87
commit 6f8b90830e
5 changed files with 45 additions and 48 deletions

View File

@ -1,17 +0,0 @@
package com.baeldung.staticvalue.injection;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@PropertySource("/application.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.staticvalue.injection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class PropertyController {
@Value("${name}")
private String name;
@Value("${name}")
private static String NAME_NULL;
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
@GetMapping("/properties")
public List<String> getProperties(){
return Arrays.asList(this.name, NAME_STATIC, NAME_NULL) ;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.staticvalueinjection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class StaticPropertyHolder {
@Value("${name}")
private static String STATIC_NAME_INJECTED_ON_FIELD;
private static String STATIC_NAME;
@Value("${name}")
public void setStaticName(String name) {
STATIC_NAME = name;
}
public static String getStaticName() {
return STATIC_NAME;
}
public static String getStaticNameInjectedOnField() {
return STATIC_NAME_INJECTED_ON_FIELD;
}
}

View File

@ -1 +1 @@
name = Inject a value to a static field
name = Inject a value to a static field

View File

@ -0,0 +1,18 @@
package com.baeldung.staticvalueinjection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = StaticPropertyHolder.class)
public class StaticPropertyHolderUnitTest {
@Test
public void givenStaticPropertyInSpringBean_WhenUsingValueOnSetter_ThenValueInjected() {
assertNull(StaticPropertyHolder.getStaticNameInjectedOnField());
assertEquals("Inject a value to a static field", StaticPropertyHolder.getStaticName());
}
}