This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,20 @@
package com.baeldung;
public class Ebook {
private int bookId;
private String bookTitle;
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
}
@@ -0,0 +1,5 @@
package com.baeldung;
public interface EbookRepository {
String titleById(int id);
}
@@ -0,0 +1,12 @@
package com.baeldung;
import org.springframework.beans.factory.annotation.Autowired;
public class LibraryUtils {
@Autowired
private EbookRepository eBookRepository;
public String findBook(int id) {
return eBookRepository.titleById(id);
}
}
@@ -0,0 +1,20 @@
package com.baeldung;
public class Member {
private int memberId;
private String memberName;
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
}
@@ -0,0 +1,14 @@
package com.baeldung;
import org.springframework.beans.factory.annotation.Autowired;
public class Reservation {
private Member member;
private Ebook eBook;
@Autowired
public Reservation(Member member, Ebook eBook) {
this.member = member;
this.eBook = eBook;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.annotation;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class MyBean {
private final TestBean testBean;
public MyBean(TestBean testBean) {
this.testBean = testBean;
System.out.println("Hello from constructor");
}
@PostConstruct
private void postConstruct() {
System.out.println("Hello from @PostConstruct method");
}
@PreDestroy
public void preDestroy() {
System.out.println("Bean is being destroyed");
}
}
@@ -0,0 +1,8 @@
package com.baeldung.annotation;
import org.springframework.stereotype.Component;
@Component
public class TestBean {
}
@@ -0,0 +1,21 @@
package com.baeldung.applicationcontext;
public class Course {
private String name;
public Course() {
}
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.applicationcontext;
import java.util.Locale;
public class Dialog {
private Locale locale;
private String hello;
private String thanks;
public Dialog() {
}
public Dialog(Locale locale, String hello, String thanks) {
this.locale = locale;
this.hello = hello;
this.thanks = thanks;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public String getThanks() {
return thanks;
}
public void setThanks(String thanks) {
this.thanks = thanks;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.applicationcontext;
public class Student {
private int no;
private String name;
public Student() {
}
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void destroy() {
System.out.println("Student(no: " + no + ") is destroyed");
}
}
@@ -0,0 +1,39 @@
package com.baeldung.applicationcontext;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
public class Teacher {
@Autowired
private ApplicationContext context;
private List<Course> courses = new ArrayList<>();
public Teacher() {
}
@PostConstruct
public void addCourse() {
if (context.containsBean("math")) {
Course math = context.getBean("math", Course.class);
courses.add(math);
}
if (context.containsBean("physics")) {
Course physics = context.getBean("physics", Course.class);
courses.add(physics);
}
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.aware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by Gebruiker on 4/24/2018.
*/
public class AwareExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(Config.class);
MyBeanName myBeanName = context.getBean(MyBeanName.class);
MyBeanFactory myBeanFactory = context.getBean(MyBeanFactory.class);
myBeanFactory.getMyBeanName();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.aware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config {
@Bean(name = "myCustomBeanName")
public MyBeanName getMyBeanName() {
return new MyBeanName();
}
@Bean
public MyBeanFactory getMyBeanFactory() {
return new MyBeanFactory();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.aware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
/**
* Created by Gebruiker on 4/25/2018.
*/
public class MyBeanFactory implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void getMyBeanName() {
MyBeanName myBeanName = beanFactory.getBean(MyBeanName.class);
System.out.println(beanFactory.isSingleton("myCustomBeanName"));
}
}
@@ -0,0 +1,11 @@
package com.baeldung.aware;
import org.springframework.beans.factory.BeanNameAware;
public class MyBeanName implements BeanNameAware {
@Override
public void setBeanName(String beanName) {
System.out.println(beanName);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.config.scope;
import java.util.function.Function;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import com.baeldung.scope.prototype.PrototypeBean;
import com.baeldung.scope.singletone.SingletonFunctionBean;
@Configuration
public class AppConfigFunctionBean {
@Bean
public Function<String, PrototypeBean> beanFactory() {
return name -> prototypeBeanWithParam(name);
}
@Bean
@Scope(value = "prototype")
public PrototypeBean prototypeBeanWithParam(String name) {
return new PrototypeBean(name);
}
@Bean
public SingletonFunctionBean singletonFunctionBean() {
return new SingletonFunctionBean();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.event.listener;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
public class ContextEventListener {
@Order(2)
@EventListener
public void handleContextRefreshEvent(ContextStartedEvent ctxStartEvt) {
System.out.println("Context Start Event received.");
}
@Order(1)
@EventListener(classes = { ContextStartedEvent.class, ContextStoppedEvent.class })
public void handleMultipleEvents() {
System.out.println("Multi-event listener invoked");
}
}
@@ -0,0 +1,10 @@
package com.baeldung.event.listener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.baeldung.event.listener")
public class EventConfig {
}
@@ -0,0 +1,12 @@
package com.baeldung.event.listener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringRunner {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(EventConfig.class);
ctx.start();
}
}
@@ -0,0 +1,23 @@
package com.baeldung.lazy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@Lazy
@Configuration
@ComponentScan(basePackages = "com.baeldung.lazy")
public class AppConfig {
@Lazy
@Bean
public Region getRegion(){
return new Region();
}
@Bean
public Country getCountry(){
return new Country();
}
}
@@ -0,0 +1,13 @@
package com.baeldung.lazy;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Lazy
@Component
public class City {
public City() {
System.out.println("City bean initialized");
}
}
@@ -0,0 +1,8 @@
package com.baeldung.lazy;
public class Country {
public Country() {
System.out.println("Country bean initialized");
}
}
@@ -0,0 +1,19 @@
package com.baeldung.lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
public class Region {
@Lazy
@Autowired
private City city;
public Region() {
System.out.println("Region bean initialized");
}
public City getCityInstance() {
return city;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.lombok;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class ApologizeService {
private final Translator translator;
private final String message;
@Autowired
public ApologizeService(Translator translator) {
this(translator, "sorry");
}
public String apologize() {
return translator.translate(message);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.lombok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class FarewellService {
private final Translator translator;
public FarewellService(Translator translator) {
this.translator = translator;
}
public String farewell() {
return translator.translate("bye");
}
}
@@ -0,0 +1,15 @@
package com.baeldung.lombok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class GreetingService {
@Autowired
private Translator translator;
public String greet() {
return translator.translate("hello");
}
}
@@ -0,0 +1,15 @@
package com.baeldung.lombok;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class ThankingService {
private final Translator translator;
public String thank() {
return translator.translate("thank you");
}
}
@@ -0,0 +1,5 @@
package com.baeldung.lombok;
public interface Translator {
String translate(String input);
}
@@ -0,0 +1,10 @@
package com.baeldung.methodinjections;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.baeldung.methodinjections")
public class AppConfig {
}
@@ -0,0 +1,19 @@
package com.baeldung.methodinjections;
import java.util.Collection;
import org.springframework.stereotype.Component;
@Component
public class Grader {
public String grade(Collection<Integer> marks) {
boolean result = marks.stream()
.anyMatch(mark -> mark < 45);
if (result) {
return "FAIL";
}
return "PASS";
}
}
@@ -0,0 +1,45 @@
package com.baeldung.methodinjections;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component("schoolNotification")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class SchoolNotification {
@Autowired
Grader grader;
private String name;
private Collection<Integer> marks;
public SchoolNotification(String name) {
this.name = name;
this.marks = new ArrayList<Integer>();
}
public String addMark(Integer mark) {
this.marks.add(mark);
return this.grader.grade(this.marks);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Integer> getMarks() {
return marks;
}
public void setMarks(Collection<Integer> marks) {
this.marks = marks;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.methodinjections;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component("studentBean")
public class Student {
private String id;
/**
* Injects a prototype bean SchoolNotification into Singleton student
*/
@Lookup
public SchoolNotification getNotification(String name) {
// spring overrides and returns a SchoolNotification instance
return null;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.methodinjections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component("studentService")
public abstract class StudentServices {
private Map<String, SchoolNotification> notes = new HashMap<>();
@Lookup
protected abstract SchoolNotification getNotification(String name);
public String appendMark(String name, Integer mark) {
SchoolNotification notification = notes.computeIfAbsent(name, exists -> getNotification(name));
return notification.addMark(mark);
}
}
@@ -0,0 +1,44 @@
package com.baeldung.scope;
import com.baeldung.scope.prototype.PrototypeBean;
import com.baeldung.scope.singletone.SingletonAppContextBean;
import com.baeldung.scope.singletone.SingletonBean;
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
import com.baeldung.scope.singletone.SingletonProviderBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan("com.baeldung.scope")
public class AppConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public PrototypeBean prototypeBean() {
return new PrototypeBean();
}
@Bean
public SingletonBean singletonBean() {
return new SingletonBean();
}
@Bean
public SingletonProviderBean singletonProviderBean() {
return new SingletonProviderBean();
}
@Bean
public SingletonAppContextBean singletonAppContextBean() {
return new SingletonAppContextBean();
}
@Bean
public SingletonObjectFactoryBean singletonObjectFactoryBean() {
return new SingletonObjectFactoryBean();
}
}
@@ -0,0 +1,24 @@
package com.baeldung.scope;
import com.baeldung.scope.prototype.PrototypeBean;
import com.baeldung.scope.singletone.SingletonBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan("com.baeldung.scope")
public class AppProxyScopeConfig {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public PrototypeBean prototypeBean() {
return new PrototypeBean();
}
@Bean
public SingletonBean singletonBean() {
return new SingletonBean();
}
}
@@ -0,0 +1,22 @@
package com.baeldung.scope;
import com.baeldung.scope.prototype.PrototypeBean;
import com.baeldung.scope.singletone.SingletonBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.util.Assert;
public class BeanInjectionStarter {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonBean firstSingleton = context.getBean(SingletonBean.class);
PrototypeBean firstPrototype = firstSingleton.getPrototypeBean();
SingletonBean secondSingleton = context.getBean(SingletonBean.class);
PrototypeBean secondPrototype = secondSingleton.getPrototypeBean();
Assert.isTrue(firstPrototype.equals(secondPrototype), "The same instance is returned");
}
}
@@ -0,0 +1,28 @@
package com.baeldung.scope.prototype;
import org.apache.log4j.Logger;
public class PrototypeBean {
private final Logger logger = Logger.getLogger(this.getClass());
public PrototypeBean() {
logger.info("Prototype instance created");
}
private String name;
public PrototypeBean(String name) {
this.name = name;
logger.info("Prototype instance " + name + " created");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.scope.singletone;
import com.baeldung.scope.prototype.PrototypeBean;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SingletonAppContextBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
public PrototypeBean getPrototypeBean() {
return applicationContext.getBean(PrototypeBean.class);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.scope.singletone;
import com.baeldung.scope.prototype.PrototypeBean;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalTime;
public class SingletonBean {
private final Logger logger = Logger.getLogger(this.getClass());
@Autowired
private PrototypeBean prototypeBean;
public SingletonBean() {
logger.info("Singleton instance created");
}
public PrototypeBean getPrototypeBean() {
logger.info(String.valueOf(LocalTime.now()));
return prototypeBean;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.scope.singletone;
import java.util.function.Function;
import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.scope.prototype.PrototypeBean;
public class SingletonFunctionBean {
@Autowired
private Function<String, PrototypeBean> beanFactory;
public PrototypeBean getPrototypeInstance(String name) {
PrototypeBean bean = beanFactory.apply(name);
return bean;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.scope.singletone;
import com.baeldung.scope.prototype.PrototypeBean;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;
@Component
public class SingletonLookupBean {
@Lookup
public PrototypeBean getPrototypeBean() {
return null;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.scope.singletone;
import com.baeldung.scope.prototype.PrototypeBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class SingletonObjectFactoryBean {
@Autowired
private ObjectFactory<PrototypeBean> prototypeBeanObjectFactory;
public PrototypeBean getPrototypeInstance() {
return prototypeBeanObjectFactory.getObject();
}
}
@@ -0,0 +1,16 @@
package com.baeldung.scope.singletone;
import com.baeldung.scope.prototype.PrototypeBean;
import org.springframework.beans.factory.annotation.Autowired;
import javax.inject.Provider;
public class SingletonProviderBean {
@Autowired
private Provider<PrototypeBean> myPrototypeBeanProvider;
public PrototypeBean getPrototypeInstance() {
return myPrototypeBeanProvider.get();
}
}
@@ -0,0 +1,35 @@
package com.baeldung.setterdi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.baeldung.setterdi.domain.Engine;
import com.baeldung.setterdi.domain.Trailer;
import com.baeldung.setterdi.domain.Transmission;
@Configuration
@ComponentScan("com.baeldung.setterdi")
public class Config {
@Bean
public Engine engine() {
Engine engine = new Engine();
engine.setType("v8");
engine.setVolume(5);
return engine;
}
@Bean
public Transmission transmission() {
Transmission transmission = new Transmission();
transmission.setType("sliding");
return transmission;
}
@Bean
public Trailer trailer() {
Trailer trailer = new Trailer();
return trailer;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.setterdi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.setterdi.Config;
import com.baeldung.setterdi.domain.Car;
public class SpringRunner {
public static void main(String[] args) {
Car toyota = getCarFromXml();
System.out.println(toyota);
toyota = getCarFromJavaConfig();
System.out.println(toyota);
}
private static Car getCarFromJavaConfig() {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
return context.getBean(Car.class);
}
private static Car getCarFromXml() {
ApplicationContext context = new ClassPathXmlApplicationContext("setterdi.xml");
return context.getBean(Car.class);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.setterdi.domain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Car {
private Engine engine;
private Transmission transmission;
private Trailer trailer;
public Car() {
}
@Autowired
public void setEngine(Engine engine) {
this.engine = engine;
}
@Autowired
public void setTransmission(Transmission transmission) {
this.transmission = transmission;
}
@Autowired
public void setTrailer(Trailer trailer) {
this.trailer = trailer;
}
@Override
public String toString() {
return String.format("Engine: %s Transmission: %s Trailer: %s", engine, transmission, trailer);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.setterdi.domain;
public class Engine {
private String type;
private int volume;
public Engine() {
}
public void setType(String type) {
this.type = type;
}
public void setVolume(int volume) {
this.volume = volume;
}
@Override
public String toString() {
return String.format("%s %d", type, volume);
}
}
@@ -0,0 +1,11 @@
package com.baeldung.setterdi.domain;
public class Trailer {
public Trailer() {
}
@Override
public String toString() {
return "Trailer";
}
}
@@ -0,0 +1,17 @@
package com.baeldung.setterdi.domain;
public class Transmission {
private String type;
public Transmission() {
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return String.format("%s", type);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.springbean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.baeldung.springbean.domain.Address;
import com.baeldung.springbean.domain.Company;
@Configuration
@ComponentScan(basePackageClasses = Company.class)
public class Config {
@Bean
public Address getAddress() {
return new Address("High Street", 1000);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.springbean.domain;
import lombok.Data;
@Data
public class Address {
private String street;
private int number;
public Address(String street, int number) {
this.street = street;
this.number = number;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.springbean.domain;
import lombok.Data;
import org.springframework.stereotype.Component;
@Data
@Component
public class Company {
private Address address;
public Company(Address address) {
this.address = address;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.streamutils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;
public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}
}
@@ -0,0 +1,11 @@
package com.baeldung.streamutils;
import java.io.InputStream;
import org.springframework.util.StreamUtils;
public class DrainStream {
public InputStream getInputStream() {
return StreamUtils.emptyInput();
}
}
@@ -0,0 +1,2 @@
spring.profiles.active=prod
@@ -0,0 +1,20 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="toyota" class="com.baeldung.constructordi.domain.Car">
<constructor-arg index="0" ref="engine"/>
<constructor-arg index="1" ref="transmission"/>
</bean>
<bean id="engine" class="com.baeldung.constructordi.domain.Engine">
<constructor-arg index="0" value="v4"/>
<constructor-arg index="1" value="2"/>
</bean>
<bean id="transmission" class="com.baeldung.constructordi.domain.Transmission">
<constructor-arg value="sliding"/>
</bean>
</beans>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="exampleDAO" class="com.baeldung.beaninjection.ExampleDAOBean">
<constructor-arg index="0" type="java.lang.String"
value="Mandatory DAO Property X" />
</bean>
<bean id="anotherSampleDAO" class="com.baeldung.beaninjection.AnotherSampleDAOBean">
<constructor-arg index="0" type="java.lang.String"
value="Mandatory DAO Property Y" />
</bean>
<bean id="exampleService" class="com.baeldung.beaninjection.ExampleServiceBean">
<constructor-arg index="0" ref="exampleDAO" />
<property name="propertyX" value="Some Service Property X"></property>
<property name="anotherSampleDAO" ref="anotherSampleDAO"></property>
</bean>
</beans>
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.baeldung.methodinjections" />
<bean id="schoolNotification" class="com.baeldung.methodinjections.SchoolNotification" scope="prototype"/>
<bean id="studentServices" class="com.baeldung.methodinjections.StudentServices" scope="prototype" >
<lookup-method name="getNotification" bean="schoolNotification"/>
</bean>
</beans>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="student" class="com.baeldung.applicationcontext.Student" destroy-method="destroy">
<property name="no" value="15"/>
<property name="name" value="Tom"/>
</bean>
<bean id="math" class="com.baeldung.applicationcontext.Course">
<property name="name" value="math"/>
</bean>
<bean name="teacher" class="com.baeldung.applicationcontext.Teacher"/>
</beans>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>dialog/dialog</value>
</list>
</property>
</bean>
</beans>
@@ -0,0 +1 @@
message.value=Hello World
@@ -0,0 +1,43 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="indexService" class="com.baeldung.di.spring.IndexService" />
<bean id="messageService" class="com.baeldung.di.spring.MessageService">
<constructor-arg value="${message.value}" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="com.baeldung.di.spring.properties" />
</bean>
<bean id="messageServiceFromStaticFactory" class="com.baeldung.di.spring.StaticServiceFactory"
factory-method="getService">
<constructor-arg value="1" />
</bean>
<bean id="indexServiceFactory" class="com.baeldung.di.spring.InstanceServiceFactory" />
<bean id="messageServiceFromInstanceFactory" class="com.baeldung.di.spring.InstanceServiceFactory"
factory-method="getService" factory-bean="indexServiceFactory">
<constructor-arg value="1" />
</bean>
<bean id="indexApp" class="com.baeldung.di.spring.IndexApp">
<property name="service" ref="indexService" />
</bean>
<bean id="indexAppWithStaticFactory" class="com.baeldung.di.spring.IndexApp">
<property name="service" ref="messageServiceFromStaticFactory" />
</bean>
<bean id="indexAppWithFactoryMethod" class="com.baeldung.di.spring.IndexApp">
<property name="service" ref="messageServiceFromInstanceFactory" />
</bean>
<bean id="messageWorldApp" class="com.baeldung.di.spring.MessageApp">
<constructor-arg ref="messageService" />
</bean>
</beans>
@@ -0,0 +1,22 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="toyota" class="com.baeldung.constructordi.domain.Car">
<constructor-arg index="0" ref="engine" />
<constructor-arg index="1" ref="transmission" />
</bean>
<bean id="engine"
class="com.baeldung.constructordi.domain.Engine">
<constructor-arg index="0" value="v4" />
<constructor-arg index="1" value="2" />
</bean>
<bean id="transmission"
class="com.baeldung.constructordi.domain.Transmission">
<constructor-arg value="sliding" />
</bean>
</beans>
@@ -0,0 +1,23 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:annotation-config/>
<bean id="articleWithSetterInjectionBean"
class="com.baeldung.dependencyinjectiontypes.ArticleWithSetterInjection">
<constructor-arg ref="textFormatterBean" />
</bean>
<bean id="articleWithConstructorInjectionBean"
class="com.baeldung.dependencyinjectiontypes.ArticleWithConstructorInjection">
<constructor-arg ref="textFormatterBean" />
</bean>
<bean id="textFormatterBean" class="com.baeldung.dependencyinjectiontypes.TextFormatter">
</bean>
</beans>
@@ -0,0 +1,3 @@
hello=hello
you=you
thanks=thank {0}
@@ -0,0 +1,3 @@
hello=\u4f60\u597d
you=\u4f60
thanks=\u8c22\u8c22{0}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="ftpReader" class="com.baeldung.beaninjection.FtpReader">
<constructor-arg value="localhost" />
<constructor-arg value="21" />
</bean>
<bean name="readerService" class="com.baeldung.beaninjection.ReaderService">
<property name="ftpReader" ref="ftpReader" />
</bean>
</beans>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,24 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="toyota" class="com.baeldung.setterdi.domain.Car">
<property name="engine" ref="engine" />
<property name="transmission" ref="transmission" />
<property name="trailer" ref="trailer" />
</bean>
<bean id="engine" class="com.baeldung.setterdi.domain.Engine">
<property name="type" value="v4" />
<property name="volume" value="2" />
</bean>
<bean id="transmission" class="com.baeldung.setterdi.domain.Transmission">
<property name="type" value="sliding" />
</bean>
<bean id="trailer" class="com.baeldung.setterdi.domain.Trailer">
</bean>
</beans>
@@ -0,0 +1,37 @@
package com.baeldung.Lazy;
import com.baeldung.lazy.AppConfig;
import com.baeldung.lazy.Country;
import com.baeldung.lazy.Region;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class LazyAnnotationUnitTest {
@Test
public void givenLazyAnnotation_whenConfigClass_thenLazyAll() {
// Add @Lazy to AppConfig.class while testing
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
ctx.getBean(Region.class);
ctx.getBean(Country.class);
}
@Test
public void givenLazyAnnotation_whenAutowire_thenLazyBean() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
Region region = ctx.getBean(Region.class);
region.getCityInstance();
}
@Test
public void givenLazyAnnotation_whenBeanConfig_thenLazyBean() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
ctx.getBean(Region.class);
}
}
@@ -0,0 +1,59 @@
package com.baeldung.applicationcontext;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import java.util.Locale;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class ClasspathXmlApplicationContextIntegrationTest {
@Test
public void testBasicUsage() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpathxmlapplicationcontext-example.xml");
Student student = (Student) context.getBean("student");
assertThat(student.getNo(), equalTo(15));
assertThat(student.getName(), equalTo("Tom"));
Student sameStudent = context.getBean("student", Student.class);// do not need cast class
assertThat(sameStudent.getNo(), equalTo(15));
assertThat(sameStudent.getName(), equalTo("Tom"));
}
@Test
public void testRegisterShutdownHook() {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpathxmlapplicationcontext-example.xml");
context.registerShutdownHook();
}
@Test
public void testInternationalization() {
MessageSource resources = new ClassPathXmlApplicationContext("classpathxmlapplicationcontext-internationalization.xml");
String enHello = resources.getMessage("hello", null, "Default", Locale.ENGLISH);
String enYou = resources.getMessage("you", null, Locale.ENGLISH);
String enThanks = resources.getMessage("thanks", new Object[] { enYou }, Locale.ENGLISH);
assertThat(enHello, equalTo("hello"));
assertThat(enThanks, equalTo("thank you"));
String chHello = resources.getMessage("hello", null, "Default", Locale.SIMPLIFIED_CHINESE);
String chYou = resources.getMessage("you", null, Locale.SIMPLIFIED_CHINESE);
String chThanks = resources.getMessage("thanks", new Object[] { chYou }, Locale.SIMPLIFIED_CHINESE);
assertThat(chHello, equalTo("你好"));
assertThat(chThanks, equalTo("谢谢你"));
}
@Test
public void testApplicationContextAware() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpathxmlapplicationcontext-example.xml");
Teacher teacher = context.getBean("teacher", Teacher.class);
List<Course> courses = teacher.getCourses();
assertThat(courses.size(), equalTo(1));
assertThat(courses.get(0).getName(), equalTo("math"));
}
}
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
- [Intro to the Spring ClassPathXmlApplicationContext](http://www.baeldung.com/spring-classpathxmlapplicationcontext)
@@ -0,0 +1,120 @@
package com.baeldung.classpathfileaccess;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.util.ResourceUtils;
/**
* Test class illustrating various methods of accessing a file from the classpath using Resource.
* @author tritty
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class SpringResourceIntegrationTest {
/**
* Resource loader instance for lazily loading resources.
*/
@Autowired
private ResourceLoader resourceLoader;
@Autowired
private ApplicationContext appContext;
/**
* Injecting resource
*/
@Value("classpath:data/employees.dat")
private Resource resourceFile;
/**
* Data in data/employee.dat
*/
private static final String EMPLOYEES_EXPECTED = "Joe Employee,Jan Employee,James T. Employee";
@Test
public void whenResourceLoader_thenReadSuccessful() throws IOException {
final Resource resource = resourceLoader.getResource("classpath:data/employees.dat");
final String employees = new String(Files.readAllBytes(resource.getFile()
.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenApplicationContext_thenReadSuccessful() throws IOException {
final Resource resource = appContext.getResource("classpath:data/employees.dat");
final String employees = new String(Files.readAllBytes(resource.getFile()
.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenAutowired_thenReadSuccessful() throws IOException {
final String employees = new String(Files.readAllBytes(resourceFile.getFile()
.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenResourceUtils_thenReadSuccessful() throws IOException {
final File employeeFile = loadEmployeesWithSpringInternalClass();
final String employees = new String(Files.readAllBytes(employeeFile.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenResourceAsStream_thenReadSuccessful() throws IOException {
final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) {
final String employees = reader.lines()
.collect(Collectors.joining("\n"));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
}
@Test
public void whenResourceAsFile_thenReadSuccessful() throws IOException {
final File resource = new ClassPathResource("data/employees.dat").getFile();
final String employees = new String(Files.readAllBytes(resource.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenClassPathResourceWithAbsoultePath_thenReadSuccessful() throws IOException {
final File resource = new ClassPathResource("/data/employees.dat", this.getClass()).getFile();
final String employees = new String(Files.readAllBytes(resource.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenClassPathResourceWithRelativePath_thenReadSuccessful() throws IOException {
final File resource = new ClassPathResource("../../../data/employees.dat", SpringResourceIntegrationTest.class).getFile();
final String employees = new String(Files.readAllBytes(resource.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
public File loadEmployeesWithSpringInternalClass() throws FileNotFoundException {
return ResourceUtils.getFile("classpath:data/employees.dat");
}
}
@@ -0,0 +1,16 @@
package com.baeldung.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
@Configuration
public class ApplicationContextTestResourceNameType {
@Bean(name = "namedFile")
public File namedFile() {
File namedFile = new File("namedFile.txt");
return namedFile;
}
}
@@ -0,0 +1,22 @@
package com.baeldung.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
@Configuration
public class ApplicationContextTestResourceQualifier {
@Bean(name = "defaultFile")
public File defaultFile() {
File defaultFile = new File("defaultFile.txt");
return defaultFile;
}
@Bean(name = "namedFile")
public File namedFile() {
File namedFile = new File("namedFile.txt");
return namedFile;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class ApologizeServiceAutowiringIntegrationTest {
private final static String TRANSLATED = "TRANSLATED";
@Autowired
private ApologizeService apologizeService;
@Autowired
private Translator translator;
@Test
public void apologizeWithTranslatedMessage() {
when(translator.translate("sorry")).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizeService.apologize());
}
}
@@ -0,0 +1,21 @@
package com.baeldung.lombok;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ApologizeServiceIntegrationTest {
private final static String MESSAGE = "MESSAGE";
private final static String TRANSLATED = "TRANSLATED";
@Test
public void apologizeWithCustomTranslatedMessage() {
Translator translator = mock(Translator.class);
ApologizeService apologizeService = new ApologizeService(translator, MESSAGE);
when(translator.translate(MESSAGE)).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizeService.apologize());
}
}
@@ -0,0 +1,31 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class FarewellAutowiringIntegrationTest {
@Autowired
private FarewellService farewellService;
@Autowired
private Translator translator;
@Test
public void sayByeWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("bye")).thenReturn(translated);
assertEquals(translated, farewellService.farewell());
}
}
@@ -0,0 +1,20 @@
package com.baeldung.lombok;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class FarewellServiceIntegrationTest {
private final static String TRANSLATED = "TRANSLATED";
@Test
public void sayByeWithTranslatedMessage() {
Translator translator = mock(Translator.class);
when(translator.translate("bye")).thenReturn(TRANSLATED);
FarewellService farewellService = new FarewellService(translator);
assertEquals(TRANSLATED, farewellService.farewell());
}
}
@@ -0,0 +1,37 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class GreetingServiceIntegrationTest {
@Autowired
private GreetingService greetingService;
@Autowired
private Translator translator;
@Test
public void greetWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("hello")).thenReturn(translated);
assertEquals(translated, greetingService.greet());
}
@Test(expected = NullPointerException.class)
public void throwWhenInstantiated() {
GreetingService greetingService = new GreetingService();
greetingService.greet();
}
}
@@ -0,0 +1,17 @@
package com.baeldung.lombok;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.mockito.Mockito.mock;
@Configuration
@ComponentScan("com.baeldung.lombok")
class TestConfig {
@Bean
public Translator mockTranslator() {
return mock(Translator.class);
}
}
@@ -0,0 +1,31 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class ThankingServiceAutowiringIntegrationTest {
@Autowired
private ThankingService thankingService;
@Autowired
private Translator translator;
@Test
public void thankWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("thank you")).thenReturn(translated);
assertEquals(translated, thankingService.thank());
}
}
@@ -0,0 +1,20 @@
package com.baeldung.lombok;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ThankingServiceIntegrationTest {
private final static String TRANSLATED = "TRANSLATED";
@Test
public void thankWithTranslatedMessage() {
Translator translator = mock(Translator.class);
when(translator.translate("thank you")).thenReturn(TRANSLATED);
ThankingService thankingService = new ThankingService(translator);
assertEquals(TRANSLATED, thankingService.thank());
}
}
@@ -0,0 +1,30 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceNameType.class)
public class FieldResourceInjectionIntegrationTest {
@Resource(name = "namedFile")
private File defaultFile;
@Test
public void givenResourceAnnotation_WhenOnField_ThenDependencyValid() {
assertNotNull(defaultFile);
assertEquals("namedFile.txt", defaultFile.getName());
}
}
@@ -0,0 +1,45 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceQualifier.class)
public class MethodByQualifierResourceIntegrationTest {
private File arbDependency;
private File anotherArbDependency;
@Test
public void givenResourceQualifier_WhenSetter_ThenValidDependencies() {
assertNotNull(arbDependency);
assertEquals("namedFile.txt", arbDependency.getName());
assertNotNull(anotherArbDependency);
assertEquals("defaultFile.txt", anotherArbDependency.getName());
}
@Resource
@Qualifier("namedFile")
public void setArbDependency(File arbDependency) {
this.arbDependency = arbDependency;
}
@Resource
@Qualifier("defaultFile")
public void setAnotherArbDependency(File anotherArbDependency) {
this.anotherArbDependency = anotherArbDependency;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceNameType.class)
public class MethodByTypeResourceIntegrationTest {
private File defaultFile;
@Resource
protected void setDefaultFile(File defaultFile) {
this.defaultFile = defaultFile;
}
@Test
public void givenResourceAnnotation_WhenSetter_ThenValidDependency() {
assertNotNull(defaultFile);
assertEquals("namedFile.txt", defaultFile.getName());
}
}
@@ -0,0 +1,34 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceNameType.class)
public class MethodResourceInjectionIntegrationTest {
private File defaultFile;
@Resource(name = "namedFile")
protected void setDefaultFile(File defaultFile) {
this.defaultFile = defaultFile;
}
@Test
public void givenResourceAnnotation_WhenSetter_ThenDependencyValid() {
assertNotNull(defaultFile);
assertEquals("namedFile.txt", defaultFile.getName());
}
}
@@ -0,0 +1,29 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceNameType.class)
public class NamedResourceIntegrationTest {
@Resource(name = "namedFile")
private File testFile;
@Test
public void givenResourceAnnotation_WhenOnField_THEN_DEPENDENCY_Found() {
assertNotNull(testFile);
assertEquals("namedFile.txt", testFile.getName());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceQualifier.class)
public class QualifierResourceInjectionIntegrationTest {
@Resource
@Qualifier("defaultFile")
private File dependency1;
@Resource
@Qualifier("namedFile")
private File dependency2;
@Test
public void givenResourceAnnotation_WhenField_ThenDependency1Valid() {
assertNotNull(dependency1);
assertEquals("defaultFile.txt", dependency1.getName());
}
@Test
public void givenResourceQualifier_WhenField_ThenDependency2Valid() {
assertNotNull(dependency2);
assertEquals("namedFile.txt", dependency2.getName());
}
}
@@ -0,0 +1,33 @@
package com.baeldung.resource;
import com.baeldung.configuration.ApplicationContextTestResourceNameType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import javax.annotation.Resource;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = ApplicationContextTestResourceNameType.class)
public class SetterResourceInjectionIntegrationTest {
private File defaultFile;
@Resource
protected void setDefaultFile(File defaultFile) {
this.defaultFile = defaultFile;
}
@Test
public void givenResourceAnnotation_WhenOnSetter_THEN_MUST_INJECT_Dependency() {
assertNotNull(defaultFile);
assertEquals("namedFile.txt", defaultFile.getName());
}
}
@@ -0,0 +1,63 @@
package com.baeldung.scope;
import com.baeldung.scope.prototype.PrototypeBean;
import com.baeldung.scope.singletone.SingletonFunctionBean;
import com.baeldung.scope.singletone.SingletonLookupBean;
import com.baeldung.scope.singletone.SingletonObjectFactoryBean;
import com.baeldung.scope.singletone.SingletonProviderBean;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfig.class)
public class PrototypeBeanInjectionIntegrationTest {
@Test
public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonObjectFactoryBean firstContext = context.getBean(SingletonObjectFactoryBean.class);
SingletonObjectFactoryBean secondContext = context.getBean(SingletonObjectFactoryBean.class);
PrototypeBean firstInstance = firstContext.getPrototypeInstance();
PrototypeBean secondInstance = secondContext.getPrototypeInstance();
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
@Test
public void givenPrototypeInjection_WhenLookup_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonLookupBean firstContext = context.getBean(SingletonLookupBean.class);
SingletonLookupBean secondContext = context.getBean(SingletonLookupBean.class);
PrototypeBean firstInstance = firstContext.getPrototypeBean();
PrototypeBean secondInstance = secondContext.getPrototypeBean();
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
@Test
public void givenPrototypeInjection_WhenProvider_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonProviderBean firstContext = context.getBean(SingletonProviderBean.class);
SingletonProviderBean secondContext = context.getBean(SingletonProviderBean.class);
PrototypeBean firstInstance = firstContext.getPrototypeInstance();
PrototypeBean secondInstance = secondContext.getPrototypeInstance();
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.scope;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.config.scope.AppConfigFunctionBean;
import com.baeldung.scope.prototype.PrototypeBean;
import com.baeldung.scope.singletone.SingletonFunctionBean;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfigFunctionBean.class)
public class PrototypeFunctionBeanIntegrationTest {
@Test
public void givenPrototypeInjection_WhenFunction_ThenNewInstanceReturn() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfigFunctionBean.class);
SingletonFunctionBean firstContext = context.getBean(SingletonFunctionBean.class);
SingletonFunctionBean secondContext = context.getBean(SingletonFunctionBean.class);
PrototypeBean firstInstance = firstContext.getPrototypeInstance("instance1");
PrototypeBean secondInstance = secondContext.getPrototypeInstance("instance2");
Assert.assertTrue("New instance expected", firstInstance != secondInstance);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.springbean;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.baeldung.springbean.domain.Company;
public class SpringBeanIntegrationTest {
@Test
public void whenUsingIoC_thenDependenciesAreInjected() {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Company company = context.getBean("company", Company.class);
assertEquals("High Street", company.getAddress().getStreet());
assertEquals(1000, company.getAddress().getNumber());
}
}
@@ -0,0 +1,100 @@
package com.baeldung.streamutils;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.util.StreamUtils;
import static com.baeldung.streamutils.CopyStream.getStringFromInputStream;
public class CopyStreamIntegrationTest {
@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copy(in, out);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(inputFileContent, outputFileContent);
}
@Test
public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copyRange(in, out, 1, 10);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(inputFileContent.substring(1, 11), outputFileContent);
}
@Test
public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
String string = "Should be copied to OutputStream.";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(string, StandardCharsets.UTF_8, out);
assertTrue(outputFile.exists());
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToString_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
assertEquals(inputFileContent, content);
}
@Test
public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
String outputFileName = "src/test/resources/output.txt";
String string = "Should be copied to OutputStream.";
byte[] byteArray = string.getBytes();
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(byteArray, out);
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream in = new FileInputStream(inputFileName);
byte[] out = StreamUtils.copyToByteArray(in);
String content = new String(out);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
assertEquals(inputFileContent, content);
}
}
@@ -0,0 +1 @@
Joe Employee,Jan Employee,James T. Employee
+1
View File
@@ -0,0 +1 @@
This file is merely for testing.
@@ -0,0 +1 @@
Should be copied to OutputStream.