Spring 基于Java的Bean声明

时间:2023-02-12 05:02:11

Spring 基于Java的Bean声明

使用@Configuration进行设置;

Xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="com.stono.sprtest"></context:component-scan>
</beans>

JavaConfig:

package com.stono.sprtest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; @Configuration
public class SingerConfig {
@Bean
@Scope("prototype")
// 如果加了这个就会导致有两个Cymbal对象;
public InstrumentI cymbal() {
return new Cymbal();
}
@Bean
public Singer3 singer3() {
// 参数里面的cymbal()不会新建Bean,还是之前那个单例实体;
return new Singer3(cymbal(), "newstr");
}
}

AppBean:

package com.stono.sprtest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AppBeans8 {
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("appbeans8.xml");
Singer3 singer3 = (Singer3) context.getBean("singer3");
System.out.println(singer3);
Object bean = context.getBean("cymbal");
System.out.println(bean);
}
}

POJO:

package com.stono.sprtest;

import org.springframework.beans.factory.annotation.Autowired;

public class Singer3 {
@Autowired
private InstrumentI instrument;
private String name;
public Singer3(InstrumentI instrument, String name) {
this.instrument = instrument;
this.name = name;
}
@Override
public String toString() {
return "Singer2 [instrument=" + instrument + ", name=" + name + "]";
}
}
package com.stono.sprtest;

public class Cymbal implements InstrumentI {
}