Java/Spring/IoC Config

Материал из Java эксперт
Перейти к: навигация, поиск

IoC in properties file

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
//File: beans.properties
# The View
view.class=StandardOutView
view.model(ref)=model
# The Model
model.class=HelloWorldModel
///////////////////////////////////////////////////////////////////////////////////////
public interface View {
    public void render();
    
    public void setModel(Model m);
    public Model getModel();
}

///////////////////////////////////////////////////////////////////////////////////////
public interface Model {
  public String getMessage();
}
///////////////////////////////////////////////////////////////////////////////////////
public class StandardOutView implements View {
    private Model model = null;
    public void render() {
        if (model == null) {
            throw new RuntimeException(
                    "You must set the property model of class:"
                            + StandardOutView.class.getName());
        }
        System.out.println(model.getMessage());
    }
    public void setModel(Model m) {
        this.model = m;
    }
    public Model getModel() {
        return this.model;
    }
}
///////////////////////////////////////////////////////////////////////////////////////

public class HelloWorldModel implements Model {
    public String getMessage() {
        return "Hello World!";
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import java.io.FileInputStream;
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
public class HelloWorldSpring {
    public static void main(String[] args) throws Exception {
        // get the bean factory
        BeanFactory factory = getBeanFactory();
        View v = (View) factory.getBean("view");
        Model mp = (Model) factory.getBean("model");
        v.setModel(mp);
        v.render();
    }
    private static BeanFactory getBeanFactory() throws Exception {
        // get the bean factory
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        // create a definition reader
        PropertiesBeanDefinitionReader rdr = new PropertiesBeanDefinitionReader(
                factory);
        // load the configuration options
        Properties props = new Properties();
        props.load(HelloWorldSpring.class.getResource("beans.properties").openStream());
        rdr.registerBeanDefinitions(props);
        return factory;
    }
}





IoC XML Config

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
//File: beans.properties
# The View
view.class=StandardOutView
view.model(ref)=model
# The Model
model.class=HelloWorldModel

///////////////////////////////////////////////////////////////////////////////////////
public interface Model {
  public String getMessage();
}

///////////////////////////////////////////////////////////////////////////////////////
public interface View {
    public void render();
    
    public void setModel(Model m);
    public Model getModel();
}

///////////////////////////////////////////////////////////////////////////////////////

public class StandardOutView implements View {
    private Model model = null;
    public void render() {
        if (model == null) {
            throw new RuntimeException(
                    "You must set the property model of class:"
                            + StandardOutView.class.getName());
        }
        System.out.println(model.getMessage());
    }
    public void setModel(Model m) {
        this.model = m;
    }
    public Model getModel() {
        return this.model;
    }
}
///////////////////////////////////////////////////////////////////////////////////////

public class HelloWorldModel implements Model {
    public String getMessage() {
        return "Hello World!";
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.io.FileInputStream;
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
public class HelloWorldSpringWithDI {
    public static void main(String[] args) throws Exception {
        // get the bean factory
        BeanFactory factory = getBeanFactory();
        View mr = (View) factory.getBean("view");
        mr.render();
    }
    private static BeanFactory getBeanFactory() throws Exception {
        // get the bean factory
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        // create a definition reader
        PropertiesBeanDefinitionReader rdr = new PropertiesBeanDefinitionReader(
                factory);
        // load the configuration options
        Properties props = new Properties();
        props.load(HelloWorldSpringWithDI.class.getResource("beans.properties").openStream());
        rdr.registerBeanDefinitions(props);
        return factory;
    }
}





Load Bean Definition From XML File

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
//File: beans.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    
    <!-- oracle bean used for a few examples -->
    <bean id="beanId" name="beanName" class="Bean"/>
    
</beans>


///////////////////////////////////////////////////////////////////////////////////////
public class Bean{
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class XmlConfigWithBeanFactory {
    public static void main(String[] args) {
        XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource(
                "build/beans.xml"));
    }
}





Lookup Demo

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
//File: lookup.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="helper" class="MyHelper" singleton="false"/>
    <bean id="abstractLookupBean" class="AbstractLookupDemoBean">
        <lookup-method name="getMyHelper" bean="helper"/>
    </bean>
    <bean id="standardLookupBean" class="StandardLookupDemoBean">
        <property name="myHelper">
            <ref local="helper"/>
        </property>
    </bean>
</beans>

///////////////////////////////////////////////////////////////////////////////////////
public interface DemoBean {
    public MyHelper getMyHelper();
    public void someOperation();
}

///////////////////////////////////////////////////////////////////////////////////////
public class MyHelper {
    public void doSomethingHelpful() {
        // do something!
    }
}
///////////////////////////////////////////////////////////////////////////////////////
public class StandardLookupDemoBean implements DemoBean {
    private MyHelper helper;
    
    public void setMyHelper(MyHelper helper) {
        this.helper = helper;
    }
    
    public MyHelper getMyHelper() {
        return this.helper;
    }
    
    public void someOperation() {
        helper.doSomethingHelpful();
    }
}
///////////////////////////////////////////////////////////////////////////////////////
public abstract class AbstractLookupDemoBean implements DemoBean {
    
    public abstract MyHelper getMyHelper();
    
    public void someOperation() {
        getMyHelper().doSomethingHelpful();
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.StopWatch;
public class LookupDemo {
    public static void main(String[] args) {
        BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
                "build/lookup.xml"));
        DemoBean abstractBean = (DemoBean) factory.getBean("abstractLookupBean");
        DemoBean standardBean = (DemoBean) factory.getBean("standardLookupBean");
        displayInfo(standardBean);
        displayInfo(abstractBean);
    }
    public static void displayInfo(DemoBean bean) {
        MyHelper helper1 = bean.getMyHelper();
        MyHelper helper2 = bean.getMyHelper();
        System.out.println("Helper Instances the Same?: "
                + (helper1 == helper2));
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("lookupDemo");
        for (int x = 0; x < 100000; x++) {
            MyHelper helper = bean.getMyHelper();
            helper.doSomethingHelpful();
        }
        stopWatch.stop();
        System.out.println("100000 gets took " + stopWatch.getTotalTimeMillis()
                + " ms");
    }
}





Simplest Usage of property config file In Spring

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
//File: msf.properties
renderer.class=StandardOutView
provider.class=HelloWorldModel

///////////////////////////////////////////////////////////////////////////////////////
public interface Model {
  public String getMessage();
}

///////////////////////////////////////////////////////////////////////////////////////

public interface View {
    public void render();
    
    public void setModel(Model m);
    public Model getModel();
}

///////////////////////////////////////////////////////////////////////////////////////

public class StandardOutView implements View {
    private Model model = null;
    public void render() {
        if (model == null) {
            throw new RuntimeException(
                    "You must set the property model of class:"
                            + StandardOutView.class.getName());
        }
        System.out.println(model.getMessage());
    }
    public void setModel(Model m) {
        this.model = m;
    }
    public Model getModel() {
        return this.model;
    }
}
///////////////////////////////////////////////////////////////////////////////////////

public class HelloWorldModel implements Model {
    public String getMessage() {
        return "Hello World!";
    }
}

///////////////////////////////////////////////////////////////////////////////////////

import java.io.FileInputStream;
import java.util.Properties;
public class MessageSupportFactory {
    private static MessageSupportFactory instance = null;
    private Properties props = null;
    private View renderer = null;
    private Model provider = null;
    private MessageSupportFactory() {
        props = new Properties();
        try {
            props.load( MessageSupportFactory.class.getResource("msf.properties").openStream());
            // get the implementation classes
            String rendererClass = props.getProperty("renderer.class");
            String providerClass = props.getProperty("provider.class");
            renderer = (View) Class.forName(rendererClass).newInstance();
            provider = (Model) Class.forName(providerClass).newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    static {
        instance = new MessageSupportFactory();
    }
    public static MessageSupportFactory getInstance() {
        return instance;
    }
    public View getView() {
        return renderer;
    }
    public Model getModel() {
        return provider;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
public class HelloWorldDecoupledWithFactory {
    public static void main(String[] args) {
        View mr = MessageSupportFactory.getInstance().getView();
        Model mp = MessageSupportFactory.getInstance().getModel();
        mr.setModel(mp);
        mr.render();
    }
}