코딩은 실력보다 시력이지

빅데이터교육과정/Spring

Spring bean Scope의 타입과 Annotation

Listeria 2021. 4. 7. 01:06

DI - Dependency Injection

데이터(객체)와 코드가 분리되어 유지보수가 쉬워지며 유연하게 사용할 수 있게 된다.

 

Singleton - 하나의 Bean 정의에 하나의 객체를 여러개의 레퍼런스가 참조. default 값이다.

Prototype - 하나의 Bean 정의에 다수의 객체를 각각의 레퍼런스를 참조한다

request - 각각의 Http request는 자신만의 객체를 가진다. Web-arare Spring ApplicationContext 안에서 유요하다.

Session - Http session 생명주기 안에 하나의 객체만 존재한다. Web-arare Spring ApplicationContext 안에서 유요하다.

Globalsession - global http session 생명주기 안에 하나의 객체만 존재. 일반적으로 portlet context 안에서 유요하다

                    Web-arare Spring ApplicationContext 안에서 유요하다.

 

   
public class Student{
	private String name;
	private int age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}
//Student 라는 bean




@Configuration
@ImportResource("classpath:applicationCTX.xml")
public class ApplicationConfig {

	@Bean
	public Student student1() {
		
		ArrayList<String> hobbys = new ArrayList<String>();
		hobbys.add("swim");
		hobbys.add("cook");
		
		Student student = new Student("hong gil dong",20,hobbys);
		student.setHeight(180);
		student.setWeight(80);
		
		return student;
		
	}
}
//configuration을 활용하여 student1 객체를 생성. 이를 메인 문에서 아래와 같이 선언하여 활용할 수 있다.
		AnnotationConfigApplicationContext ctx
		= new AnnotationConfigApplicationContext(ApplicationConfig.class);
        
        Student student1 = ctx.getBean("student1",Student.class);
		System.out.println("name : "+ student1.getName());
		System.out.println("age : " + student1.getAge());
		System.out.println("hobbys : " + student1.getHobbys());
		System.out.println("Height : " + student1.getHeight());
		System.out.println("Weight : " + student1.getWeight());
		
  <context:annotation-config/>
	<bean class="com.sl.student.ApplicationConfig"/>

		<bean id ="student2" class="com.sl.student.Student" c:name="hong gil soon" c:age="18" >
		<constructor-arg>
			<list>
			<value>reading</value>
			<value>listening</value>
			</list>
		</constructor-arg>
		<property name="height" value="170"></property>
		<property name="Weight" value = "55"></property>
        
 // 위와 같이 각각의 java 파일로 생성하여 사용하던지 혹은
 xml 파일에서 annotation을 직접 사용하여 객체를 생성할 수 있다.

'빅데이터교육과정 > Spring' 카테고리의 다른 글

GET,POST,Annotation,Bean을 활용한 회원가입 MVC2  (0) 2021.04.12
Spring MVC 패턴  (0) 2021.04.09
AOP란?  (0) 2021.04.09