Created
November 19, 2017 12:10
-
-
Save isopov/0483fe10e8c11555bd455fbc81c9af6e to your computer and use it in GitHub Desktop.
Autowired on initialized final field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.finalautowired; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.stereotype.Component; | |
@SpringBootApplication | |
public class FinalAutowiredApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(FinalAutowiredApplication.class, args); | |
} | |
@Bean | |
public Bar bar() { | |
return new Bar("context"); | |
} | |
} | |
@Component | |
class Foo { | |
@Autowired | |
private final Bar bar = new Bar("simple"); | |
public String getMessage() { | |
return bar.getMessage(); | |
} | |
} | |
class Bar { | |
private final String message; | |
public Bar(String message) { | |
this.message = message; | |
} | |
public String getMessage() { | |
return message; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.finalautowired; | |
import static org.junit.Assert.assertEquals; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.test.context.SpringBootTest; | |
import org.springframework.test.context.junit4.SpringRunner; | |
@RunWith(SpringRunner.class) | |
@SpringBootTest | |
public class FinalAutowiredApplicationTests { | |
@Autowired | |
private Foo foo; | |
@Test | |
public void test() { | |
assertEquals("simple", foo.getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment