* @Primary annotation

* @Primary annotation Employee name

* Update PrimaryApplication.java

* @Primary annotation with @Component
This commit is contained in:
Mher Baghinyan 2018-07-25 08:26:18 +04:00 committed by Grzegorz Piwowarek
parent f431a4c3ff
commit 189e62603b
7 changed files with 112 additions and 0 deletions

View File

@ -0,0 +1,22 @@
package org.baeldung.primary;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
@ComponentScan(basePackages="org.baeldung.primary")
public class Config {
@Bean
public Employee JohnEmployee(){
return new Employee("John");
}
@Bean
@Primary
public Employee TonyEmployee(){
return new Employee("Tony");
}
}

View File

@ -0,0 +1,11 @@
package org.baeldung.primary;
import org.springframework.stereotype.Component;
@Component
public class DepartmentManager implements Manager {
@Override
public String getManagerName() {
return "Department manager";
}
}

View File

@ -0,0 +1,20 @@
package org.baeldung.primary;
/**
* Created by Gebruiker on 7/17/2018.
*/
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
'}';
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.primary;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
public class GeneralManager implements Manager {
@Override
public String getManagerName() {
return "General manager";
}
}

View File

@ -0,0 +1,8 @@
package org.baeldung.primary;
/**
* Created by Gebruiker on 7/19/2018.
*/
public interface Manager {
String getManagerName();
}

View File

@ -0,0 +1,17 @@
package org.baeldung.primary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Gebruiker on 7/19/2018.
*/@Service
public class ManagerService {
@Autowired
private Manager manager;
public Manager getManager() {
return manager;
}
}

View File

@ -0,0 +1,20 @@
package org.baeldung.primary;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class PrimaryApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(Config.class);
Employee employee = context.getBean(Employee.class);
System.out.println(employee);
ManagerService service = context.getBean(ManagerService.class);
Manager manager = service.getManager();
System.out.println(manager.getManagerName());
}
}