Rectangle 27 113

Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.

When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.

So basically the id attribute conforms to the XML id attribute standards whereas name is a little more flexible. Generally speaking, I use name pretty much exclusively. It just seems more "Spring-y".

You prefer to use the "name" attribute even though Spring reference that you've quoted recommends using the "id" attribute? Even if you prefer to stick with "name", you can't call it more "Spring-y" if Spring reference suggests otherwise :) This is nitpicky, I know ;)

Difference between using bean id and name in Spring configuration file...

spring configuration
Rectangle 27 66

Since Spring 3.1 the id attribute is an xsd:string and permits the same range of characters as the name attribute.

The only difference between an id and a name is that a name can contain multiple aliases separated by a comma, semicolon or whitespace, whereas an id must be a single value.

From the Spring 3.2 documentation:

In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.

Difference between using bean id and name in Spring configuration file...

spring configuration
Rectangle 27 118

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML definitions.

More to learn about beans and scope from SpringSource:

When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes

So these are objects that the container manages and I don't have to touch, but if I want access to a bean to maybe call some methods or retrieve properties, then I can "ask" Spring for the bean?

@grantmc It's sort of like that, except the inversion of control thing is supposed to be understood as the contrary of "ask": instead of "asking" for things, you "declare" that you'll need it. And then, when you startup the app, the framework will check all declarations and set the appropriate instance.

@elias How do I declare that I need it? Is it when I'm using @Autowired? Or simply when I do my imports?

It would be helpful to define what IoC means for Spring newcomers.

java - What in the world are Spring beans? - Stack Overflow

java spring grails
Rectangle 27 116

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML definitions.

More to learn about beans and scope from SpringSource:

When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes

So these are objects that the container manages and I don't have to touch, but if I want access to a bean to maybe call some methods or retrieve properties, then I can "ask" Spring for the bean?

@grantmc It's sort of like that, except the inversion of control thing is supposed to be understood as the contrary of "ask": instead of "asking" for things, you "declare" that you'll need it. And then, when you startup the app, the framework will check all declarations and set the appropriate instance.

@elias How do I declare that I need it? Is it when I'm using @Autowired? Or simply when I do my imports?

It would be helpful to define what IoC means for Spring newcomers.

java - What in the world are Spring beans? - Stack Overflow

java spring grails
Rectangle 27 2

Unfortunately configuration from properties files is static and happens at startup. What I am typically doing is exposing dynamic attributes via jmx:

@ManagedResource
@Service
public class BusinessService {

    @ManagedAttribute
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void businessMethod() {
        //use age...
    }

}
<context:mbean-export/>

To your configuration. Now you can access and change that attribute via jconsole or any other JMX client. See also: 23.3.2 Using Source-Level Metadata (JDK 5.0 annotations).

Property files are not necessarily static - they can reside somewhere in the filesystem and be changed by ops. You are right: one can use other mechanisms to update configuration values, but I'd like to use the nice Spring placeholder mechanism. Otherwise - how would you update, say, a timeout for a WebserviceTemplate without much glue code?

WebserviceTemplate

Spring: how to do transparent runtime changeable property configuratio...

spring configuration properties
Rectangle 27 1

This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported n their originating module.

  • control over which beans are exported and where they are used
  • reduced possibility of naming collisions of beans
moduleDefinitions.xml
serverModule.xml
clientModule.xml
<?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:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    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.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />

</beans>

thanks @SpaceTrucker! seems like you've created exactly what we also need. not sure why rich spring community didn't create something similar before...

spring - Splitting applicationContext to multiple files - Stack Overfl...

spring configuration
Rectangle 27 1

This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported n their originating module.

  • control over which beans are exported and where they are used
  • reduced possibility of naming collisions of beans
moduleDefinitions.xml
serverModule.xml
clientModule.xml
<?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:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    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.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />

</beans>

thanks @SpaceTrucker! seems like you've created exactly what we also need. not sure why rich spring community didn't create something similar before...

spring - Splitting applicationContext to multiple files - Stack Overfl...

spring configuration
Rectangle 27 1

@ContextConfigurationdefines class-level metadata that is used to determine how to load and configure an ApplicationContextfor integration tests. Specifically @ContextConfigurationdeclares the application context resourcelocations or the annotatedclassesthat will be used to load the context.

@ContextConfiguration("/test-config.xml") 
public class XmlApplicationContextTests { 
    // class body... 
}

Spring Boot provides a @SpringBootTest annotation which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContextused in your tests viaSpringApplication.

You can use thewebEnvironment attribute of@SpringBootTestto further refine how your tests will run.

The search algorithm works up from the package that contains the test until it finds a@SpringBootApplicationor @SpringBootConfiguration annotated class. As long as youve structured your codein a sensible way your main configuration is usually found.

If you want to customize the primary configuration, you can use a nested @TestConfigurationclass. Unlike a nested@Configurationclass which would be used instead of a your applications primary configuration, a nested@TestConfigurationclass will be used in addition to your applications primary configuration.

I tried many solutions following your advices however none worked so far, could you provide an exemple on this ?

java - Spring boot: Unit test and Config file - Stack Overflow

java spring unit-testing configuration
Rectangle 27 8

@Profile({"!console", "!dev"}) means (NOT console) OR (NOT dev) which is true if you run your app with the profile 'console'. To solve this you can create a custom Condition:

public class NotConsoleAndDevCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        return !environment.acceptsProfiles("console", "dev");
    }
}

And apply the condition via the @Conditional annotation to the Configuration:

@Conditional(NotConsoleAndDevCondition.class)
public class MyConfigurationB {

java - Spring Boot Configuration skip registration on multiple @Profil...

java spring spring-boot spring-profiles
Rectangle 27 9

i want to know ,how it wires the dependancy.

Using the Java reflection API. I added that information to the answers.

Using Java reflection API, spring will understand that it has to insert a dependency at that particular point, but how does this dependency exactly inserted? it is some bytecode level change?

The actual injection is performed via reflection API as well - Method setFooMethod = class.getMethod("setFoo", Foo.class); setFooMethod.invoke(newObject, fooToInject);

I've seen proxy mentioned a couple of times here and there, if it is done through reflection, why do we need the proxy which requires an interface

java - How does dependency injection work in Spring? - Stack Overflow

java spring dependency-injection
Rectangle 27 2

So, you have a yaml like this:

cors:
    hosts:
        allow: 
            - http://foo1/
            - http://foo2/
            - http://foo3/

Then you first bind the data

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConfigurationProperties(prefix="cors.hosts")
public class AllowedHosts {
    private List<String> HostNames; //You can also bind more type-safe objects
}

Then in another component you just do

@Autowired
private AllowedHosts allowedHosts;

And you are done!

Worked for me! But I had to create my class as static otherwise I got beaninstantiationexception saying it was missing default construction.

configuration - Spring Boot: read list from yaml using @Value or @Conf...

spring configuration spring-boot yaml snakeyaml
Rectangle 27 2

More effective solution to avoid copying is to place all the beans that are common for both projects in a separate XML configuration file, say "common-beans.xml". And in the configuration XML file for the project B (and any other project that needs those beans) you import that file like this:

<import resource="common-beans.xml" />
<?xml version="1.0" encoding="UTF-8"?>
<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.2.xsd"

    <!-- 
         Assuming common-beans.xml is a Spring config file
         that contains the definitions you need to use
         in the current project. 
    -->
    <import resource="common-beans.xml" />

    <!-- Defining a bean with the implementaion you need -->
    <bean name="searchHelper" class="com.test.SearchHelperBImpl"/>

    <!-- Some other configurations if needed -->

</beans>

java - Overriding Spring bean - Stack Overflow

java spring
Rectangle 27 1

In short, the metadata change is desirable which enables configuration of a higher layer of abstraction rather than change in the application code. The configurable higher layer is then reusable and your lower layer of application code is easily testable. Dependency injection is one of the very old core design principles featuring in famous SOLID design principles. This design principle has featured into lots of frameworks out there - Spring being one of the most popular and evangelist of DI in Java world. There are already lots of good articles available to understand the necessity of DI- you can read them on Wikipedia and Microsoft library. And yes, then there are few gem of articles on Martin Fowler's site to understand it in depth here and here.

dependency injection - Spring How its helpful - Stack Overflow

spring dependency-injection
Rectangle 27 17

Project build lifecycle mapping can be configured in a project's pom.xml, contributed by Eclipse plugins, or defaulted to the commonly used Maven plugins shipped with m2e. We call these "lifecycle mapping metadata sources". m2e will create error marker like below for all plugin executions that do not have lifecycle mapping in any of the mapping metadata sources.

  • either by adding the lifecycleMappingMetadata in the parent pom.
  • or by enclosing the plugins with the <pluginManagement> tag (in both pom).

when taking a look in the Eclipse-UI in the project properties under Maven -> Lifecyle Mapping (having checked the Show lifecycle phases checkbox and disabled Show ignored executions), I see the following content. To my understanding this file shows the mapping between the Eclipse build lifecycle (runtime/incremental) and its bound Maven plugins. Currently, it does not contain the jax-ws plugin respectively its goal wsimport.

The problem is that you have the jax-ws plugin declared in the pluginManagement section. To get a binding to a phase it should be in build/plugins. Performing a Maven build from CLI wouldn't work either, so I suspect that you're not doing the standard "mvn install"?

To get the Maven execution from within Eclispe to work you don't have to do anything. But if you want to have incremental/runtime support in the IDE you should get the proper m2e connector. If you look at the pom in the POM editor in Eclipse, the plugin execution should be marked with a red error X. Hover on that and you should get an option to find one ("Discover new m2e connectors").

So, the only way seems to be adding lifecycle mapping metadata in parent pom to ignore the jax-ws plugin like in wiki.eclipse.org/. When I say Discover new m2e connectors, eclipse couldn't find one for the jax-ws plugin. However, when I am doing mvn clean install from the CLI, ws-import goal is running.

java - Plugin execution not covered by lifecycle configuration error i...

java eclipse maven
Rectangle 27 17

Project build lifecycle mapping can be configured in a project's pom.xml, contributed by Eclipse plugins, or defaulted to the commonly used Maven plugins shipped with m2e. We call these "lifecycle mapping metadata sources". m2e will create error marker like below for all plugin executions that do not have lifecycle mapping in any of the mapping metadata sources.

  • either by adding the lifecycleMappingMetadata in the parent pom.
  • or by enclosing the plugins with the <pluginManagement> tag (in both pom).

when taking a look in the Eclipse-UI in the project properties under Maven -> Lifecyle Mapping (having checked the Show lifecycle phases checkbox and disabled Show ignored executions), I see the following content. To my understanding this file shows the mapping between the Eclipse build lifecycle (runtime/incremental) and its bound Maven plugins. Currently, it does not contain the jax-ws plugin respectively its goal wsimport.

The problem is that you have the jax-ws plugin declared in the pluginManagement section. To get a binding to a phase it should be in build/plugins. Performing a Maven build from CLI wouldn't work either, so I suspect that you're not doing the standard "mvn install"?

To get the Maven execution from within Eclispe to work you don't have to do anything. But if you want to have incremental/runtime support in the IDE you should get the proper m2e connector. If you look at the pom in the POM editor in Eclipse, the plugin execution should be marked with a red error X. Hover on that and you should get an option to find one ("Discover new m2e connectors").

So, the only way seems to be adding lifecycle mapping metadata in parent pom to ignore the jax-ws plugin like in wiki.eclipse.org/. When I say Discover new m2e connectors, eclipse couldn't find one for the jax-ws plugin. However, when I am doing mvn clean install from the CLI, ws-import goal is running.

java - Plugin execution not covered by lifecycle configuration error i...

java eclipse maven
Rectangle 27 1

Expanding on this since the bounty wanted some elaboration: Spring doesn't wire up beans by default in unit tests. That's why those annotations are needed. I'll try to break them down a little bit:

  • @IntegrationTest (which is now deprecated in favor of @SpringBootTest ) from the docs:
  • Uses SpringBootContextLoader as the default ContextLoader when no specific @ContextConfiguration(loader=...) is defined.
  • Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit classes are specified.
  • @WebAppConfiguration adds the application context, and must be used with...
  • @ContextConfiguration actually determines how to load the "class-level" metadata.

Without these annotations, Spring doesn't wire up the beans necessary for your test configuration. This is partially for performance reasons (most tests don't need the context configured).

could you please add some notes about using Spring (not SpringBoot)?

@ The latter two annotations are not specific to Spring Boot. I think the first one could be replaced with something like "@RunWith" but I'm not sure as I've only ever used these with Spring Boot. What are you specifically trying to do?

java - Context Configuration in spock test - Stack Overflow

java spring spock applicationcontext
Rectangle 27 0

You can very well use both XML based metadata and Annotation based configuration metadata in your application. The configuration metadata is the information how you tell the Spring container to instantiate, configure, and assemble the objects in your application. Configuration metadata is traditionally supplied in a simple and intuitive XML format. i.e XML based configuration metadata. Spring 2.5 introduced support for annotation-based configuration metadata.Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus, you have different ways of providing your configuration metadata of your application through XML, Annotation based and Java config from Spring 3.x versions. This link will take you in the right direction. You must have to learn IOC chapter in Spring documentation

java - How to stick with both XML and Annotation based configuration S...

java xml spring spring-mvc annotations
Rectangle 27 0

You should check configuration part of the spring reference. For example you can create beans like this with spring 3.x.

@Configuration
// spring config that loads the properties file
@ImportResource("classpath:/properties-config.xml")
public class AppConfig {

    /**
     * Using property 'EL' syntax to load values from the
     * jetProperties value
     */
    private @Value("#{jetProperties['jetBean.name']}") String name;
    private @Value("#{jetProperties['jetBean.price']}") Long price;
    private @Value("#{jetProperties['jetBean.url']}") URL url;

    /**
     * Create a jetBean within the Spring Application Context
     * @return a bean
     */
    public @Bean(name = "jetBean")
    JetBean jetBean() {
        JetBean bean = new JetBeanImpl();
        bean.setName(name);
        bean.setPrice(price);
        bean.setUrl(url);
        return bean;
    }

}

Yes, but this still requires a pre-defined properties file that contains the required jetProperties definitions. I would like these to be specified at runtime. Perhaps I can look into creating these properties on the fly.

java - How do I provide runtime specific configuration metadata to Spr...

java spring dependency-injection factory
Rectangle 27 0

If you need to create a bean for ServletContext in a XML config spring application, you could use a BeanFactory<ServletContext> implementing ServletContextAware

public class ServletContextFactory implements FactoryBean<ServletContext>,
            ServletContextAware{
    private ServletContext servletContext;

    @Override
    public ServletContext getObject() throws Exception {
        return servletContext;
    }

    @Override
    public Class<?> getObjectType() {
        return ServletContext.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

}

You can then declare :

<bean class="org.app.ServletContextFactory" id="servletContext" />

<bean class="com.abc.ProductController">
    <property name="servletContext" ref="servletContext"/>
</bean>

java - How to set ServletContext property for a bean in Spring XML met...

java xml spring spring-mvc
Rectangle 27 0

Spring - Bean Definition

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions which you have already seen in previous chapters.

The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

All the above configuration metadata translates into a set of the following properties that make up each bean definition.

PropertiesDescription
classThis attribute is mandatory and specify the bean class to be used to create the bean.
nameThis attribute specifies the bean identifier uniquely. In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s).
scopeThis attribute specifies the scope of the objects created from a particular bean definition and it will be discussed in bean scopes chapter.
constructor-argThis is used to inject the dependencies and will be discussed in next chapters.
propertiesThis is used to inject the dependencies and will be discussed in next chapters.
autowiring modeThis is used to inject the dependencies and will be discussed in next chapters.